2011-09-22 201 views
1

我有以下JSON對象。如何閱讀json

{"feed":[ 
    {"news": 
     {"adopted_from":null,"user_id":null,"description":"this is test","id":2} 
    }, 
    {"news": 
    {"adopted_from":null,"user_id":null,"description":"like unlike done","id":1} 
    } 
]} 

我想要檢索的新聞ID。我嘗試了許多不同的方式(例如feed[0].news.id,feed.news.id,feed[[0].news.id]),但無法訪問該值。任何人都可以幫助我如何使用JavaScript訪問它?

回答

2

我複製和粘貼上面的JSON和嘗試了以下內容和它的作品只是罰款:


    var data = {"feed":[{"news":{"adopted_from":null,"user_id":null,"description":"this is test","id":2}},{"news":{"adopted_from":null,"user_id":null,"description":"like unlike done","id":1}}]}; 
    // alert the first news id 
    alert(data.feed[0].news.id); 

它從陣列第一news對象獲取ID作爲預期。

1

這個工作對我來說:

var f = {"feed":[{"news":{"adopted_from":null,"user_id":null,"description":"this is test","id":2}},{"news":{"adopted_from":null,"user_id":null,"description":"like unlike done","id":1}}]} 
alert(f.feed[0].news.id) 
0
var feed = json_decode(yourData) 
for(var counter in feed) { 
    console.log(feed[counter].news.id); 
}