[英]Nested JSON Object not showing up when printing it
無法顯示深層嵌套的JSON對象,因此一直在查看各種stackoverflow帖子。 感謝這個新手問題的幫助。 我希望它在運動者數組中顯示運動者JSONObject的詳細信息。 它顯示為[Object]。
eventUnitResults: [ { is_team: true, athletes: [ [Object], [Object] ] },
{ is_team: true, athletes: [ [Object], [Object] ] } ]
const result = {} let eventUnitResults = []; let athletes = []; for (i=0; i < 2; i++) { const athlete = {}; athlete.athlete_name = 'Ram' + i; athlete.athlete_gender = 'M' athletes.push(athlete); } for (j=0;j < 2;j++) { const nestedResult = {}; nestedResult.is_team = true; if (athletes) { nestedResult.athletes = athletes; } console.log('nestedResult:', nestedResult); if (nestedResult) { eventUnitResults.push(nestedResult);//TODO: //eventUnitResults.push(JSON.stringify(nestedResult));//TODO: } } console.log('eventUnitResults:', eventUnitResults);//<==== how can I get deeply nested values of athletes showing up properly here if (eventUnitResults) { result.event_unit_results = eventUnitResults; } console.log('result:', result)
TIA
如果您記錄對象,則可能需要將實際對象轉換為字符串。
如果將此與Java(或大多數語言)進行比較:
System.out.println(object);
打印您的object.toString()
。 除非您覆蓋它,否則就是內存地址。
在JavaScript中:
console.log(object);
[object, object]
將打印[object, object]
因為它會打印您要打印的內容。 在這種情況下,它不知道您期望包含JSON的字符串。
請注意,這並不適用於所有瀏覽器。 例如,Chrome希望幫助您並以交互方式打印JSON值; 您可以折疊和收起它。
解決此問題的方法是明確告知控制台打印json字符串。 您可以通過調用內置json對象的函數來對對象進行字符串化來實現。
JSON.stringify(object);
{“ content”:“ json”}
為了完整起見,可以通過將打印輸出設置為4個空格縮進來漂亮地打印對象:
JSON.stringify(object, null, 4);
打印:
{
"content": "json"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.