如何根据“架构”过滤 JSON 对象

How to filter JSON objects according to "schema"

本文关键字:过滤 JSON 对象 架构 何根      更新时间:2023-09-26

我用node.js构建了一个RESTful api,并表达了/koa。

我想过滤 JSON 数据输入 - 出于安全原因,也只有所需的业务特定属性。筛选后,将进行特定于业务的验证。

如何丢弃不需要的JSON/JS对象属性 - 即不在数据库架构中的属性以及空属性?

  • 根据此定义架构和过滤器?例如使用 https://github.com/alank64/json-schema-filter
  • 是否有可配置的过滤可用?

我认为joi是一个很好的验证和规范化库。您有时也可以侥幸逃脱一些简单的事情,例如 _.pick from lodash/underscore。

您可以考虑使用 JSON 架构验证器。

http://json-schema.org/implementations.html

验证器基准:https://github.com/ebdrup/json-schema-benchmark

免责声明:我创建了 ajv

从文档中,joi.validate() 可以去除字段,但只能删除 Object 字段。 我写了这个,可以在要点中可用,这似乎工作正常。 它返回一个新对象,仅包含比较对象中与架构对象中的相应字段具有相同名称和类型的字段:

// Recursively strip out fields in objects and subobjects
function stripFields(schema, obj) {
  var newObj = {};
  var schemaType = schema.constructor.name;
  var objType = obj.constructor.name;
  // If types match and this property is not an Object, return the value
  if (schemaType !== "Object") {
    if(schemaType === objType) {
      return obj;
    } else {
      return null;
    }
  }
  var keys = Object.keys(schema);
  keys.forEach(function(key) {
    if(key in obj) {
      // Get instance names for properties
      var schemaConstructor = schema[key].constructor.name;
      var objConstructor = obj[key].constructor.name;
      // Only copy fields with matching types.
      if (schemaConstructor === objConstructor) {
        // Handle cases with subObjects
        if (objConstructor === "Object") {
          var res = stripFields(schema[key], obj[key]);
          if (res !== null) {
            newObj[key] = res;
          }
        } else {
          //  Just copy in non-Object properties (String, Boolean, etc.)
          newObj[key] = obj[key];
        }
      }
    };
    if (newObj === {}) {
      return null;
    }
  });
  return newObj;
}

以下测试用例正确删除了不正确的字段:

var stripFields = require("./stripfields");
var schema = {
  a: 1, 
  b: 1,
  c:{ 
      foo:"bar",
      obj:{nestedField:1}
  },
  d:[1]
};
var testObj1 = {
  a: 7,
  b: 8,
  c:{
      foo:"bar"
  },
  d:[4,5]
};
var testObj2 = {
  a: 1,
  b: 2,
  c:{
      foo:"bar",
      obj:{nestedField:213}
  },
  d:[1,3,4],
  e:"someOtherField"
};
var testObj3 = {
  a: 1,
  c:{
      foo:"some string",
      bar:1
  },
  d:"string instead of array"
};

var res1 = stripFields(schema, testObj1);
var res2 = stripFields(schema, testObj2);
var res3 = stripFields(schema, testObj3);
var res4 = stripFields([1,2,3], ["a"]);
console.log("Results:");
console.log(res1);
console.log(res2);
console.log(res3);
console.log(res4);

结果:

Results:
{ a: 7, b: 8, c: { foo: 'bar' }, d: [ 4, 5 ] }
{ a: 1,
  b: 2,
  c: { foo: 'bar', obj: { nestedField: 213 } },
  d: [ 1, 3, 4 ] }
{ a: 1, c: { foo: 'some string' } }
[ 'a' ]