0

我有一个这样的 JSON 对象:

{"photos":
   {"page":1,
    "pages":414,
    "perpage":10,
    "total":"4136",
    "photo":[
         {
            "id":"13193333",
            "owner":"picture owner",
            "title":"picture title",
            "lat":43.81919,
            "lon":11.294719,
            "url":"http:\\...."
         },
         {
            "id":"13193383",
            "owner":"picture owner",
            "title":"picture title",
            "lat":43.81919,
            "lon":11.294719,
            "url":"http:\\...."
         },

        ... (other items of "photo" like the two above).......
    ]},
    "stat":"ok"}

根据 JSONPath 规范,如果我想选择所有“标题”,我将使用:

$.photos.photo[*].title

现在,对于我的 JSON 数据中的每个不同属性,我需要以一般方式获取其 JSONPath 字符串(例如,我不需要完全“标题”的 JSONpath - 像$.photos.photo[1].title- 但一般的 JSONpath - like $.photos.photo[*].title)。

编辑:我会尝试更好地解释(对不起我的英语不好!),我想要做的是以这种方式获取与每个属性相关的 JSONPath:

JSON attribute: "photos"
JSONPath("photos") = $.photos

JSON attribute: "photo"
JSONPath("photo") = $.photos.photo[*]

JSON attribute: "title"
JSONPath("title") = $.photos.photo[*].title

等等...

如何用 JS 或 PHP 语言解决这个问题?谢谢!

4

3 回答 3

0

您可以使用 DefiantJS ( http://defiantjs.com ),它使用“搜索”方法扩展全局对象 JSON。使用此方法,您可以使用 XPath 查询您的 JSON 结构,并将匹配项作为类似数组的对象返回。

这是一个示例片段;

var data = {
       "photos": {
          "page": 1,
          "pages": 414,
          "perpage": 10,
          "total": "4136",
          "photo": [
             {
                "id": "13193333",
                "owner": "picture owner 1",
                "title": "picture title 1",
                "lat": 43.81919,
                "lon": 11.294719,
                "url": "http:\\...."
             },
             {
                "id": "13193383",
                "owner": "picture owner 2",
                "title": "picture title 2",
                "lat": 43.81919,
                "lon": 11.294719,
                "url": "http:\\...."
             }
          ]
       },
       "stat": "ok"
    },
    found = JSON.search(data, "//title"),
    str = '';

for (var i=0; i<found.length; i++) {
    str += found[i] +'<br/>';
}

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

要查看此操作,请查看此小提琴;http://jsfiddle.net/hbi99/4t4gb/

这里有更多有用的 XPath 查询示例;http://defiantjs.com/#xpath_evaluator

于 2014-05-18T21:21:07.283 回答
0

我认为您可以在这里使用 for 循环:

for(var photo in $.photos) {
    console.log(photo.title);
}

或推送到数组

var arr = new Array();
for(var photo in $.photos) {
    arr.push(photo.title);
}
于 2014-03-21T16:29:04.880 回答
0

如果您只想将值设置到键标题中,您可以在 JS 中执行此操作:

var titles = [];
for( i in $.photos.photo ){
    var photo = $.photos.photo[i];
    titles.push( photo.title );
    console.log( photo.title );
}

或者在 PHP 中:

$titles = array();
$array = json_decode( $your_json_string, true );
foreach( $array['photos']['photo'] as $a ){
    $titles[] = $a['title'];
}
// now in $titles you have all titles :)

如果你想在这里你可以看到 json_decode 函数的 PHP 文档。

问候,

凯文

于 2014-03-21T16:35:09.510 回答