我有一个像这样的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 - 类似$.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语言解决这个问题?谢谢!
答案 0 :(得分:0)
我认为你可以在这里使用for循环:
for(var photo in $.photos) {
console.log(photo.title);
}
或推送到数组
var arr = new Array();
for(var photo in $.photos) {
arr.push(photo.title);
}
答案 1 :(得分: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 :)
如果你想要here,你可以看到json_decode函数的PHP文档。
此致
凯文
答案 2 :(得分:0)
您可以使用DefiantJS(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