我需要解析一个包含 json 的字符串。我需要确保输出是一个JsonRecord
而不是一个 json 原语。
我已经尝试使用fp-ts
andio-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
还是我应该使用其他东西?