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规范,如果我想选择所有的"title",我将使用:
$.photos.photo[*].title
现在,对于JSON数据中的每个不同属性,我需要以一般方式获得其JSONPath字符串(例如,我不需要确切的"title"JSONPath -如$.photos.photo[1].title
-但一般JSONPath -如$.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语言解决这个问题?谢谢!
我认为你可以在这里使用for循环:
for(var photo in $.photos) {
console.log(photo.title);
}
或压入数组
var arr = new Array();
for(var photo in $.photos) {
arr.push(photo.title);
}
如果你只想把值设置到键标题中,你可以在JS中这样做:
var titles = [];
for( i in $.photos.photo ){
var photo = $.photos.photo[i];
titles.push( photo.title );
console.log( photo.title );
}
或PHP中的this:
$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文档
问候,凯文
你可以使用defantjs (http://defiantjs.com),它通过"search"方法扩展了全局对象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