搜索JSON以获取多个值,而不是使用库

时间:2012-10-16 08:27:54

标签: json search

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

示例返回:

  

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"
      }
   ]
};

1 个答案:

答案 0 :(得分:0)

@vsiege - 您可以使用此javascript lib(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使用“搜索”方法扩展全局对象JSON,并且可以使用XPath表达式查询JSON(XPath是标准化查询语言)。该方法返回一个带匹配的数组(如果没有找到则为空数组)。

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