繁体   English   中英

纯JS JSON解析来自本地JSON文件的许多对象

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM