0

我希望能够在以下 JSON 对象中搜索包含键“位置”的对象,然后返回一个数组或 json 对象,其中包含该人的“名称”加上该人的位置值。

样品退货:

var matchesFound = [{Tom Brady, New York}, {Donald Steven,Los Angeles}];

var fbData0 = {
   "data": [
      {
         "id": "X999_Y999",
         "location": "New York",
         "from": {
            "name": "Tom Brady", "id": "X12"
         },
         "message": "Looking forward to 2010!",
         "actions": [
            {
               "name": "Comment",
               "link": "http://www.facebook.com/X999/posts/Y999"
            },
            {
               "name": "Like",
               "link": "http://www.facebook.com/X999/posts/Y999"
            }
         ],
         "type": "status",
         "created_time": "2010-08-02T21:27:44+0000",
         "updated_time": "2010-08-02T21:27:44+0000"
      },
      {
         "id": "X998_Y998",
         "location": "Los Angeles",
         "from": {
            "name": "Donald Steven", "id": "X18"
         },
         "message": "Where's my contract?",
         "actions": [
            {
               "name": "Comment",
               "link": "http://www.facebook.com/X998/posts/Y998"
            },
            {
               "name": "Like",
               "link": "http://www.facebook.com/X998/posts/Y998"
            }
         ],
         "type": "status",
         "created_time": "2010-08-02T21:27:44+0000",
         "updated_time": "2010-08-02T21:27:44+0000"
      }
   ]
};
4

1 回答 1

0

@vsiege - 您可以使用这个 javascript 库 ( http://www.defiantjs.com/ ) 来搜索您的 JSON 结构。

var fbData0 = {
   ...
},
res = JSON.search( fbData0, '//*[./location and ./from/name]' ),
str = '';

for (var i=0; i<res.length; i++) {
    str += res[i].location +': '+ res[i].from.name +'<br/>';
}

document.getElementById('output').innerHTML = str;

这是一个工作小提琴;
http://jsfiddle.net/hbi99/XhRLP/

DefiantJS 使用“search”方法扩展了全局对象 JSON,并使得使用 XPath 表达式查询 JSON 成为可能(XPath 是标准化的查询语言)。该方法返回一个包含匹配项的数组(如果没有找到则为空数组)。

您可以通过在此处粘贴 JSON 来测试 XPath 表达式:http:
//www.defiantjs.com/#xpath_evaluator

于 2014-01-05T07:12:35.217 回答