2014-02-17 84 views
1

我有以下JSON,我想要解析的是,當我想要的是當「keyYear」或「docType」鍵時,所有「名稱」和「計數」。我可以遍歷摘要並獲取「pubYear」和「docType」的所有名稱和計數,但我無法獲得單個的名稱和計數。任何建議?我使用JQuery來解析這個。解析多維JSON數組,嵌套數組

{ 
    "summaries": [ 
    { 
     "name": "Publication Year", 
     "pubYear": [ 
     { "name": "2001", "count": 9, "stars": "1 Star" }, 
     { "name": "2009", "count": 24, "stars": "4 Stars" }, 
     { "name": "2010", "count": 3, "stars": "2 Stars" } 
     ] 
    }, 
    { 
     "name": "Document type", 
     "docType": [ 
     { "name": "Book", "count": 20 }, 
     { "name": "Journal", "count": 2 } 
     ] 
    } 
    ]  
} 

$.getJSON("js/init.json", function(json) { 
$.each(json.summaries, function(key, data) { 
     $.each(data.docType, function(entryIndex, entry) { 
     console.log(this.name); 
     }); 
    }); 
    }); 
+0

你說的 「不能讓個別」 呢?你能展示你現在擁有的循環嗎? –

+0

我添加了循環 – AlexCon

+1

您可能想要在循環之前檢查'data'是否具有'docType'或'pubYear'屬性。但是,你有什麼問題?你在哪裏遇到麻煩?你想做什麼? –

回答

0

你可以像這樣做,

HTML:

<button class="pubYear" >pubYear</button> 
<button class="docType" >docType</button> 

JQUERY:

var json=JSON.parse('{ "summaries": [ {  "name": "Publication Year",  "pubYear": [  { "name": "2001", "count": 9, "stars": "1 Star" },  { "name": "2009", "count": 24, "stars": "4 Stars" },  { "name": "2010", "count": 3, "stars": "2 Stars" }  ] }, {  "name": "Document type",  "docType": [  { "name": "Book", "count": 20 },  { "name": "Journal", "count": 2 }  ] } ]  }'); 
$('button.pubYear,button.docType').click(function(){ 
    var but=$(this).attr('class') 
    var but1=but=="pubYear"?0:1; 
    $.each(json.summaries[but1][but],function(){ 
     console.log(this.name+' : '+this.count); 
    }); 
}) 

Fiddle Demo

爲了獲得個人的價值做,

json.summaries[1].docType[0].name 
json.summaries[1].docType[1].name 

Fiddle Demo