如何循环访问每个对象。问题是我无法访问JSON
结构内的多维数组,它返回[object] [object]
。我的JSON
结构看起来像这样。
{
"expirationDate": "August 31, 2016",
"remainingDays": 127,
"pid": "TE80",
"seats": [{
"activeStatus": "Y",
"pid": "TE80",
"firstName": "Lenovo X230 Beta SN",
"guid": "0CA6A94E378F464E9A5EC09102779CFC"
}]
}
答案 0 :(得分:0)
您需要使用括号表示法来获取数组中的属性键。
seats[0].guid
在这个特殊的JSON中:
seats
数组只有一个对象
该对象有4个键/值对
所以为了得到任何东西,它总是seats[0]
和.key
seats[0].activeStatus
,seats[0].pid
,seats[0].firstName
和seats[0].guid
var data =
'{"expirationDate": "August 31, 2016",'+
'"remainingDays": 127,'+
'"pid": "TE80",'+
'"seats": [{'+
'"activeStatus": "Y",'+
'"pid": "TE80",'+
'"firstName": "Lenovo X230 Beta SN",'+
'"guid": "0CA6A94E378F464E9A5EC09102779CFC"}]}';
function JSONObj(json) {
var jsonObj = JSON.parse(json);
return jsonObj;
}
function processLog(result) {
console.log('Result: ' + result);
}
var status = JSONObj(data).expirationDate;
var GUID = JSONObj(data).seats[0].guid;
var first = JSONObj(data).seats[0].firstName;
<ol>
<li>Separate into segments (see script)</li>
<li>Wrap each segment with single quotes `'`</li>
<li>Add a `+` after each segment</li>
</ol>
<button onclick="processLog(status);">EXPIRES</button>
<button onclick="processLog(GUID);">GUID</button>
<button onclick="processLog(first);">NAME</button>