簡體   English   中英

如何根據“模式”過濾JSON對象

[英]How to filter JSON objects according to “schema”

我用node.js和express / koa構建一個RESTful api。

我想過濾JSON數據輸入 - 出於安全原因以及只有所需的業務特定屬性。 過濾后,將進行特定於業務的驗證。

如何丟棄不需要的JSON / JS對象屬性 - 即不在我的數據庫模式中的屬性以及空屬性?

我認為joi是一個很好的驗證和規范化庫。 你有時也可以從lodash / underscore中獲取像_.pick這樣簡單的東西。

您可以考慮使用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' ]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM