我有一組json數據已經通過url輸出。數據有不同的級別,我需要訪問一個級別,然後在jquery循環中使用這些數據來操作一些函數。如何從json數據的輸出中獲取特定的數據?
JSON的URL輸出數據是這樣的:
{
"id": 32,
"title": "sascas",
"synopsis": "<p>cxcxcx</p>\r\n",
"body": "<p>cxccxxc</p>\r\n",
"created_at": "2014-09-25T14:12:06.345Z",
"updated_at": "2014-09-25T14:12:06.345Z",
"author": {
"name": "A test author",
"biography": "/system/authors/avatars/000/000/024/original/photo.JPG?1411472688",
"id": 24
},
"schools": {
"schools": [
{
"id": 5,
"school_name": "Another london school Inner Circle Regent's Park, London",
"website": null,
"book_id": 32,
"created_at": "2014-09-25T14:12:06.413Z",
"updated_at": "2014-09-25T14:12:06.413Z"
},
{
"id": 6,
"school_name": "city of london school 107 Queen Victoria St London",
"website": null,
"book_id": 32,
"created_at": "2014-09-25T14:12:06.417Z",
"updated_at": "2014-09-25T14:12:06.417Z"
}
]
}
}
我基本上是試圖訪問只在一個js函數中這個循環的學校數據。目前該功能使用每個循環並將標記添加到地圖上。我想知道的是,我的功能只能獲取學校數據嗎?這是我爲它js函數:
var initMap = function() {
# The url that is generated in the html for me to grab
var info = $('#map').data('book-title');
$.get(info, {}, function(response) {
setMarkers(map, response);
# some other js stuff for map here inside the $get
}, 'json');
}
在setmarkers功能
然後,我有這樣的:在控制檯
function setMarkers(map, json) {
jQuery.each(json, function (index, city) {
var school = city['schools'];
console.log(school);
});
}
在輸出我得到這個:
[Object, Object]0: Object book_id: 32 created_at: "2014-09-25T14:12:06.413Z"id: 5school_name: "Another london school Inner Circle Regent's Park, London" updated_at: "2014-09-25T14:12:06.413Z" website: null__proto__: Object__define Getter__: function __defineGetter__() { [native code] }__defineSetter__: function __defineSetter__() { [native code] }__lookupGetter__: function __lookupGetter__() { [native code] }__lookupSetter__: function __lookupSetter__() { [native code] }constructor: function Object() { [native code] }hasOwnProperty: function hasOwnProperty() { [native code] }isPrototypeOf: function isPrototypeOf() { [native code] }propertyIsEnumerable: function propertyIsEnumerable() { [native code] }toLocaleString: function toLocaleString() { [native code] }toString: function toString() { [native code] }valueOf: function valueOf() { [native code] }get __proto__: function __proto__() { [native code] }set __proto__: function __proto__() { [native code] }1: Objectbook_id: 32created_at: "2014-09-25T14:12:06.417Z"id: 6school_name: "city of london school 107 Queen Victoria St London"updated_at: "2014-09-25T14:12:06.417Z"website: null__proto__: Objectlength: 2__proto__: Array[0]
我需要訪問該陣列中的特定數據,即school_name
。這可能嗎?
當然。 '城市['學校']'是一系列學校,所以只需重複一遍即可。請參閱[訪問/進程(嵌套)對象,數組或JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – 2014-09-25 16:43:01
Felix是一個嚮導。如果他提到你的文章,請閱讀文章。研究它。明白它。真正的幸福將是你的。 – gibberish 2014-09-25 16:50:12
我可以使用'console.log(data ['school_name']);'獲得一所學校的名字,但這已經在.each循環中了,所以我做了'jQuery.each(json ['schools']),函數(索引,城市)',它通過數組並獲取學校數據。我只需要在循環內部獲取每個學校的名稱就可以了。 – 2014-09-25 17:34:53