[英]Pure JS json parsing with many objects from local JSON file
我對如何使用json感到困惑。 直到現在,我一直都不得不使用“ in-code”數組,我很樂意反復進行此類操作。
現在我必須解析json文件並從中獲取數據,但是我對DOM元素的輸出是:
[object Object],[object Object],[object Object],[object Object]
等等等等。
有人能請我解釋一下我應該如何使事情正常嗎?
我目前的代碼:
<h1 id="json" onclick="json();">click</h1>
<script>
function json(){
$.getJSON("./assets/songs.json", function(json) {
console.log(json);
document.getElementById('json').innerHTML = json.songs;
});
}
鏈接到我使用的.json文件: 單擊
function json(){ var url = "http://davidpots.com/jakeworry/017%20JSON%20Grouping,%20part%203/data.json"; $.getJSON(url, function (json) { console.log(JSON.stringify(json.songs)); document.getElementById('json').innerHTML = JSON.stringify(json.songs); }); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <h1 id="json" onClick="json()">click</h1> </body>
使用JSON.stringify(json)
以字符串格式獲取JSON。
我會說這是正確的行為。 json.songs
是要輸出到DOM的JavaScript對象數組。 如果要顯示json.songs
內容,則必須遍歷對象並使用實際值。
也許這段代碼可以說明不同之處:
const json = JSON.parse('{"songs":[{"title":"1904","artist":"The Tallest Man on Earth","year":"2012","web_url":"http://www.songnotes.cc/songs/78-the-tallest-man-on-earth-1904","img_url":"http://fireflygrove.com/songnotes/images/artists/TheTallestManOnEarth.jpg"},{"title":"#40","artist":"Dave Matthews","year":"1999","web_url":"http://www.songnotes.cc/songs/119-dave-matthews-40","img_url":"http://fireflygrove.com/songnotes/images/artists/DaveMatthews.jpg"}]}'); // Put the objects inside the <p> document.querySelector(".objects").textContent = json.songs // Put a string of the objects in the <p> document.querySelector(".objectString").textContent = JSON.stringify(json.songs); // Use the actual value document.querySelector(".value").textContent = json.songs[0].artist;
<p class="objects"></p> <p class="objectString"></p> <p class="value"></p>
對於JSON
轉換,有兩個功能:
JSON.parse()
>>接受JSON
作為參數並返回javascript對象 JSON.stringify()
>>接受JS對象作為參數並返回JSON
字符串 例如:
let Object = { prop1: 1, prop2: 2 } let JSONstring = JSON.stringify(Object); console.log(JSONstring); console.log(typeof JSONstring); let objectAgain = JSON.parse(JSONstring); console.log(objectAgain); // bugs in SO try in JSbin console.log(typeof objectAgain);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.