你用什么类库校验 json 数据的格式?

#1

服务端返回的数据有时候细节不对应, 你觉得用什么类库校验比较好? 有什么好的实践吗?

#2

用 ramda 的 where 方法

http://ramdajs.com/docs/#where

// pred :: Object -> Boolean
var pred = R.where({
  a: R.equals('foo'),
  b: R.complement(R.equals('bar')),
  x: R.gt(R.__, 10),
  y: R.lt(R.__, 20)
});

pred({a: 'foo', b: 'xxx', x: 11, y: 19}); //=> true
pred({a: 'xxx', b: 'xxx', x: 11, y: 19}); //=> false
pred({a: 'foo', b: 'bar', x: 11, y: 19}); //=> false
pred({a: 'foo', b: 'xxx', x: 10, y: 19}); //=> false
pred({a: 'foo', b: 'xxx', x: 11, y: 20}); //=> false
1 Like
#3

ramda 整个库都是基于 curry 的,所以即便单独引用该方法,体积仍然会比较大,视场景而定

#4

看上去动态特性挺多的. 应该跟 TypeScript 没有什么好的支持吧?

#5
interface specObjInterface {
  a: (o: string) => boolean;
  b: (o: string) => boolean;
  x: (o: number) => boolean;
}

interface testObjInterface {
  a: string;
  b: string;
  x: number;
}

const specObj: specObjInterface = {
  a: R.equals('foo'),
  b: R.complement(R.equals('bar')),
  x: R.flip(R.gt(10))
}

const testObj: testObjInterface = {
  a: 'foo',
  b: 'bar',
  x: 9
}

const isPass = R.where(specObj, testObj);

if (isPass) {
  console.log(1);
}

目前 ts 主要还是判断函数的类型是否正确,而 where 函数主要还是负责运行时的容错校验,上述例子中可以直接看出 isPassFalse ,但是 ts 编译后的代码仍然会保留


const specObj = {
    a: R.equals('foo'),
    b: R.complement(R.equals('bar')),
    x: R.flip(R.gt(10))
};
const testObj = {
    a: 'foo',
    b: 'bar',
    x: 9
};
const isPass = R.where(specObj, testObj);
if (isPass) {
    console.log(1);
}