2011-03-02 57 views
10

您好,我有以下JSON對象:如何訪問JSON對象中的數組?

[ 
{ 
    "comments":[ 
    { 
    "created_at":"2011-02-09T14:42:42-08:00", 
    "thumb":"xxxxxxx", 
    "level":1,"id":214, 
    "user_id":41, 
    "parent_id":213, 
    "content":"<p>xxxxxx</p>", 
    "full_name":"xx K" 
    }, 
    { 
    "created_at":"2011-02-09T14:41:23-08:00", 
    "thumb":"xxxxxxxxxxxxx", 
    "level":0, 
    "id":213, 
    "user_id":19, 
    "parent_id":null, 
    "content":"<p>this is another test</p>", 
    "full_name":"asd asd asd asd asd" 
    } 
    ], 
"eee1":"asdadsdas", 
"eee2":"bbbbb" 
} 
] 

這是從$.ajax請求到來,成功,我有....

success: function (dataJS) { 
     console.log(dataJS); 
     console.log(dataJS[eee1]); 
     console.log(dataJS.comments); 
    } 

問題是我無法訪問即使dataJS在控制檯中正確顯示,也是如此。想法?

感謝

+0

console.log(dataJS.comments [0]); ? – orolo 2011-03-02 21:21:10

+0

您是否檢查過響應頭的內容類型確實是application/json? – jimmystormig 2011-03-02 21:22:13

回答

5

你回來的JSON實際上是一個數組本身,所以...

dataJS[0].comments[0].created_at 

2011-02-09T14:42:42-08:00等..

兩個dataJScomments是數組,並需要索引來訪問適當的元素。

+0

這不好嗎?我錯誤地構建了JSON對象嗎? – AnApprentice 2011-03-02 21:20:34

+0

不,它不是根據規範構建的,所以不是不正確的,但是你想用什麼語法來訪問它? – jondavidjohn 2011-03-02 21:22:55

+0

好吧,這就是我需要知道的。謝謝!我會接受一旦stackoverflow讓我... – AnApprentice 2011-03-02 21:25:03

3

被返回的對象本身是一個數組,所以去的第一條評論(作爲一個例子),這是你將如何訪問:

dataJS[0].comments[0]

-2

JSON必須eval功能解釋(明顯的消毒後,請參閱eval的安全考慮)。你確定你的框架爲你做了嗎?

+1

是的,jQuery評估JSON。 – BoltClock 2011-03-02 21:21:35

+0

隱含''.ajax'和jquery標籤 – jondavidjohn 2011-03-02 21:22:13

+5

'eval'是邪惡的。 – 2011-03-02 21:24:30

9

這是因爲您的基礎對象也是一個數組。

console.log(dataJS[0].comments[0]); 

我懷疑,將工作

3
console.log(dataJS); 
console.log(dataJS[0].eee1); 
console.log(dataJS[0].comments[0]); 
1

做這樣的事情: -

var dataJS = [{"comments":[{"created_at":"2011-02-09T14:42:42-08:00","thumb":"xxxxxxx","level":1,"id":214,"user_id":41,"parent_id":213,"content":"<p>xxxxxx</p>","full_name":"xx K"},{"created_at":"2011-02-09T14:41:23-08:00","thumb":"xxxxxxxxxxxxx","level":0,"id":213,"user_id":19,"parent_id":null,"content":"<p>this is another test</p>","full_name":"asd asd asd asd asd"}],"eee1":"asdadsdas","eee2":"bbbbb"}]; 

var created_at = dataJS[0].comments[0].created_at; 
1

是的,正如其他人所說,JSON實際上是一個單一對象的數組( )。所以你需要引用一個索引。

有趣的是(對我),你的結果串併成功驗證爲JSON。我認爲直到現在,要成爲有效的JSON,它必須是一個對象(即{})。

+1

數組也成功驗證爲JSON ... – 2011-03-02 21:34:39

0

您必須在ajax請求中將dataType提爲'JSON'。讓用戶像下面那樣做。

$.ajax({ 
      url: $('#frmAddCourse').attr('action'), 
      type: 'POST', 
      data: $('#frmAddCourse').serialize(), 
      dataType: 'JSON', 
      success: function (data){ 
       Materialize.toast(data['state'],2000); 
      }, 
      error:function(){ 
       Materialize.toast(errorMessage,2000); 
      } 
     });