首页 > 解决方案 > 如果我不知道 JSON 的结构是单个、数组或嵌套的深层结构,请在 JSON 中通过键和值查找对象

问题描述

我可以随机面对三种类型的 JSON,

拳种、对象:

{ "a" : "b", "@type" : "Product" }

第二种类型,数组:

[{ "a" : "b", "@type" : "Test" }, { "a" : "b", "@type" : "Product" }]

第三种,嵌套对象:

{ "d" : "e", "f" : { "a" : "b", "@type" : "Product" } }

我正在尝试获取包含“@type”:“Product”的对象,因此我想要[{ "a" : "b", "@type" : "Product" }]的结果将适用于所有类型。

为了得到这个结果,如果是第二个,我可以使用obj.filter(d => d["@type"]=="Product")and 作为第一个,创建一个空数组,var empty_array = []; empty_array.push(obj)然后使用与第二个相同的过滤器。

但是,当属性位于嵌套对象中时,我不知道如何获得所需的结果。

是否有任何 JSON 过滤器可以为所有类型获得所需的结果?

当我使用 JsonPath 时,我$..[?(@["\x40type"] =="Product"在 Json 中进行了深度搜索,并且效果很好,但是我想在 Javascript 本身中找到方法。

提前谢谢了 :)

标签: javascriptjson

解决方案


你能试试下面的方法吗

// This method will return the type of object. In case of array or JSON, it will return array or json instead of object.
function getType(obj) {
  if (typeof obj === 'object') {
     if (Array.isArray(obj)) {
      return 'array';
     }
     return 'json';
  }
  return typeof obj;
}

// This method will return either the required JSON or null.
function getObject(obj) {
  // Check the type if it is JSON.
  if (getType(obj) === 'json') {
    // If the current object has a key named @type, return the object.
    if (Object.keys(obj).includes('@type') && obj['@type'] === 'Product') return obj;
    // Otherise call the method recursively for each value of JSON.
    const values = Object.values(obj);
    for (let i = 0, n = values.length; i < n; ++i) {
      const returnVal = getObject(values[i]);
      // If the value is required JSON, return that value.
      if (returnVal) return returnVal;
    }
  // Check if the type of object is array.
  } else if (getType(obj) === 'array') {
    // Call the function recursively for each value of the array.
    for (let i = 0, n = obj.length; i < n; ++i) {
      const returnVal = getObject(obj[i]);
      // If you get the required JSON, return it.
      if (returnVal) return returnVal;
    }
  }
  // If you didn't get the required JSON, return null.
  return null;
}

var a = { "a" : "b", "@type" : "Product" };
var b = [{ "a" : "b", "@type" : "Test" }, { "a" : "b", "@type" : "Product" }];
var c = { "d" : "e", "f" : { "a" : "b", "@type" : "Product" } };

console.log(getObject(a));
console.log(getObject(b));
console.log(getObject(c));


推荐阅读