解析动态JSON对象

时间:2019-04-24 18:00:58

标签: javascript arrays json reactjs parsing

我正在解析JSON,并在该JSON对象中搜索特定的键。问题在于JSON的结构不断变化,我无法对路径进行硬编码,有没有更好的解析方法?

我可以将其转换为如下所示的常规JSON键值对

{
"resourceName": "Bundle",
"id": "6d6e-81d5-5a1e2b452563",
"lastUpdated": "2069-06-21",
"url": "http://abcd.com",
.
.
.
... so on 
}

我尝试使用硬编码方法,但这似乎并不总是有效

这里是JSON的片段

{
    "resourceName": "Bundle",
    "id": "6d6e-81d5-5a1e2b452563",
    "meta": {
        "lastUpdated": "2069-06-21"
    },
    "data1": [{
        "url": "http://abcd.com",
        "value": {
            "url": "http://abcd.com",
            "value": [{
                "url": "Severity",
                "value": "info"
            }, {
                "url": "dfew",
                "value": "fefdd"
            }, {
                "url": "fwef",
                "value": "This is data blah blah"
            }]
        }
    }]
}

2 个答案:

答案 0 :(得分:0)

您以递归方式搜索对象:

function get_lastUpdated(obj)
{
  for ( var key in obj )
  {
    if ( key == "lastUpdated" ) return obj[key];
    if ( typeof obj[key] == "object" )
    {
      var res = get_lastUpdated(obj[key]);
      if ( res ) return res;
    }
  }
  return null;
}

在一个简单的情况下,类似上面的内容可能会起作用。

答案 1 :(得分:0)

调用JSON.parse时,可以传入一个称为reviver的回调函数,该函数将递归应用于所有键值对。例如:

var jsonString = `{
    "resourceName": "Bundle",
    "id": "6d6e-81d5-5a1e2b452563",
    "meta": {
        "lastUpdated": "2069-06-21"
    },
    "data1": [{
        "url": "http://abcd.com",
        "value": {
            "url": "http://abcd.com",
            "value": [{
                "url": "Severity",
                "value": "info"
            }, {
                "url": "dfew",
                "value": "fefdd"
            }, {
                "url": "fwef",
                "value": "This is data blah blah"
            }]
        }
    }]
}`;

var obj = {};
JSON.parse(jsonString, (key, value) => {
  if (typeof value === "string" && !(key in obj)) {
    obj[key] = value;
  }
});

console.log(obj);

如果已经解析了对象,则可以对JSON.stringifyreplacer回调使用类似的策略:

var data = {
    "resourceName": "Bundle",
    "id": "6d6e-81d5-5a1e2b452563",
    "meta": {
        "lastUpdated": "2069-06-21"
    },
    "data1": [{
        "url": "http://abcd.com",
        "value": {
            "url": "http://abcd.com",
            "value": [{
                "url": "Severity",
                "value": "info"
            }, {
                "url": "dfew",
                "value": "fefdd"
            }, {
                "url": "fwef",
                "value": "This is data blah blah"
            }]
        }
    }]
};

var obj = {};
JSON.stringify(data, (key, value) => {
  if (typeof value === "string" && !(key in obj)) {
    obj[key] = value;
  }
  return value;
});

console.log(obj);