【问题标题】:How to parse and validate a JsonRecord with io-ts?如何使用 io-ts 解析和验证 JsonRecord?
【发布时间】:2021-01-26 13:29:19
【问题描述】:

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

我已尝试为此使用fp-tsio-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 是否正确,或者我应该使用其他东西?

【问题讨论】:

    标签: fp-ts


    【解决方案1】:

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

    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');
    });
    

    【讨论】:

      猜你喜欢
      • 2019-12-17
      • 2021-09-18
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      • 2016-11-05
      • 2019-04-21
      • 1970-01-01
      相关资源
      最近更新 更多