[英]Accessing nested properties json
我有這個json:
{"objects":[{"text":{"x":643,"y":71,"width":82,"height":33,"font":"Arial","style":"bold","size":24,"label":"Part A"}},
{"text":{"x":643,"y":116,"width":389,"height":42,"font":"Arial","style":"bold","size":16,"label":"What does \"novel\" mean as it is used in paragraph 8 of \"Turning Down a New Road\"? "}},
{"radiobutton":{"x":643,"y":170,"width":100,"height":20,"label":"A. old"}},{"radiobutton":{"x":643,"y":209,"width":100,"height":20,"label":"B. afraid"}},
{"radiobutton":{"x":643,"y":250,"width":100,"height":20,"label":"C. new"}},
{"radiobutton":{"x":643,"y":289,"width":100,"height":20,"label":"D. friendly"}}]}
我需要獲取每個元素的屬性,但是我無法獲取第二級的屬性,我的意思是我不知道元素是“文本”、“單選按鈕”、“標簽”,我沒有問題具有三級屬性。
這是我的來源:
$.ajax({
url: 'generateobject.php',
dataType: 'json',
type: 'GET'
}).done(function(data) {
$.each(data, function(index, firstLevel) {
$.each(firstLevel, function(anotherindex, secondLevel) {
alert(secondLevel[0]);//shows [object Object]
$.each(secondLevel, function(yetAnotherIndex, thirdLevel) {
//alert(thirdLevel.y+''+thirdLevel.y);
});
});
});
});
如何獲得二級屬性?
使用Object.keys(data)
並訪問第一項。 如果您運行該代碼段,您應該會看到預期的類型警報:
var data = {"objects":[{"text":{"x":643,"y":71,"width":82,"height":33,"font":"Arial","style":"bold","size":24,"label":"Part A"}}, {"text":{"x":643,"y":116,"width":389,"height":42,"font":"Arial","style":"bold","size":16,"label":"What does \\"novel\\" mean as it is used in paragraph 8 of \\"Turning Down a New Road\\"? "}}, {"radiobutton":{"x":643,"y":170,"width":100,"height":20,"label":"A. old"}},{"radiobutton":{"x":643,"y":209,"width":100,"height":20,"label":"B. afraid"}}, {"radiobutton":{"x":643,"y":250,"width":100,"height":20,"label":"C. new"}}, {"radiobutton":{"x":643,"y":289,"width":100,"height":20,"label":"D. friendly"}}]}; $.each(data, function(index, firstLevel) { $.each(firstLevel, function(anotherindex, secondLevel) { alert(Object.keys(secondLevel)[0]); $.each(secondLevel, function(yetAnotherIndex, thirdLevel) { //alert(thirdLevel.y+''+thirdLevel.y); }); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.