2016-08-25 80 views
-1

我有一個JSON對象返回,看起來像這樣JSON JavaScript的顯示值未定義

[ 
    { 
     "competition": { 
      "name": "Premier League", 
     }, 
     "nextState": 1, 
     "team_id": 1 
}, { 
     "competition": { 
      "name": "Premier League", 
     }, 
     "nextState": 1, 
     "team_id": 2 
} 
] 

了JSON這是一個簡化版本,我想訪問說TEAM_ID

result = JSON.stringify(result, null, 4); 
    console.log(result); 

    $('#test').append(result); 

    alert(result[0].team_id); 

所有我似乎得到的是未定義的,我沒有正確訪問它?

非常感謝

+0

' 「[」 .team_id'將永遠是不確定的。不要將其字符串化 –

+0

您正在將數據結構(JSON)轉換爲字符串(字符串)。難怪你無法再訪問數據結構。現在,每個人在發送之前都會因爲某種原因將JSON串起來,之後一直收到它,這是我無法解釋的一種趨勢。 –

+0

感謝大家,所有的答案都非常有幫助,接受的答案是第一,儘管感謝大家。 –

回答

0

你已字符串化的對象result爲字符串。所以肯定你不能訪問屬性了。

使用的字符串化結果的第二個變量:

var result_stringified = JSON.stringify(result, null, 4); 
console.log(result_stringified); 
$('#test').append(result_stringified); 
alert(result[0].team_id); 
+0

非常感謝 –

0

試試這個:

var data = [{ 
     "competition": { 
     "name": "Premier League", 
     }, 
     "nextState": 1, 
     "team_id": 1 
    }, { 
     "competition": { 
     "name": "Premier League", 
     }, 
     "nextState": 1, 
     "team_id": 2 
    }] 



    $.each(data, function(k, v) { 
     alert(this.team_id); 
    }) 
0

爲什麼你看到undefined是因爲你已經字符串化的JSON對象轉換爲字符串已原因。所以一個String!=數組,因此做String [0]會給你不確定的,顯然做一個undefined的.team_id仍然是undefined

你在那裏有一個array的javascript objects

要訪問對象的特定屬性team_id,首先必須從陣列訪問object然後使用.team_id符號或在object["team_id"]語法。

例子:

var items =[ 
 
    { 
 
     "competition": { 
 
      "name": "Premier League", 
 
     }, 
 
     "nextState": 1, 
 
     "team_id": 1 
 
    }, 
 
    { 
 
     "competition": { 
 
      "name": "Premier League", 
 
     }, 
 
     "nextState": 1, 
 
     "team_id": 2 
 
    } 
 
] 
 

 
items.forEach(item => { console.log("item_id= " + item.team_id + ", competition= " + item.competition.name); });

我已經在上面的例子做的是,我現在用的是forEach API要經過items陣列的各個項目,然後我打印通過訪問其team_id和嵌套competition.name屬性的object的詳細信息。

只要您有興趣在.forEach() API。

參見:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach