0

我需要解析一个包含 json 的字符串。我需要确保输出是一个JsonRecord而不是一个 json 原语。

我已经尝试使用fp-tsandio-ts为此。到目前为止,我知道这t.UnknownRecord.decode将返回一个Either. 这将left用于原始和right记录。我不确定如何与parseJSON. 当我尝试时,我得到类型错误。请参阅下面测试之间的评论。

import { pipe } from "fp-ts/lib/function";
import * as E from "fp-ts/lib/Either";
import * as t from "io-ts";

const onLeft = () => "NO";
const onRight = () => "YES";

describe("parsing strings of json", () => {
  it("should return a right for a json record", () => {
    const record: E.JsonRecord = { banana: "yellow fruit" };
    expect(t.UnknownRecord.decode(record)).toEqual(E.right(record));
  });

  it("should not return a right for a json primitive", () => {
    const primitive: E.Json = "banana is a yellow fruit";
    expect(t.UnknownRecord.decode(primitive)).not.toEqual(
      E.right(primitive)
    );
  });

  it("should say YES for a string containing a json record", () => {
    expect(
      pipe(
        E.parseJSON('{"banana":"yellow fruit"}', E.toError),
        E.chain(t.UnknownRecord.decode),
        E.fold(onLeft, onRight)
      )
    ).toEqual("YES");
  });

  //  Argument of type 'Either<Error, Json>' is not assignable to parameter of type     'Either<Errors, unknown>'.
  //    Type 'Left<Error>' is not assignable to type 'Either<Errors, unknown>'.
  //      Type 'Left<Error>' is not assignable to type 'Left<Errors>'.
  //        Type 'Error' is missing the following properties from type 'Errors': length, pop, push, concat, and 28 more.

  it("should say NO for a string containing a json primitive", () => {
    expect(
      pipe(
        E.parseJSON('"banana is a yellow fruit"', E.toError),
        E.chain(t.UnknownRecord.decode),
        E.fold(onLeft, onRight)
      )
    ).toEqual("NO");
  });
});

在这里尝试使用是正确的chain还是我应该使用其他东西?

4

1 回答 1

0

在得到一些建议后,我现在知道答案如下:

import * as f from 'fp-ts/lib/function';
...
it('should say YES for a string containing a json record', () => {
  expect(
    f.pipe(
      E.parseJSON('{"banana":"yellow fruit"}', E.toError),
      E.chain(f.flow(t.UnknownRecord.decode, E.mapLeft(E.toError))),
      E.fold(onLeft, onRight)
    )
  ).toEqual('YES');
});

it('should say NO for a string containing a json primitive', () => {
  expect(
    f.pipe(
      E.parseJSON('"banana is a yellow fruit"', E.toError),
      E.chain(f.flow(t.UnknownRecord.decode, E.mapLeft(E.toError))),
      E.fold(onLeft, onRight)
    )
  ).toEqual('NO');
});
于 2021-01-31T15:19:11.530 回答