我花了数小时寻找使用JS读取JSON文件。 我发现的最接近的是这https://gist.github.com/zuch/6224600。从文件中读取后无法访问JSON内容
cells.json:
{
"cells": [
{
"img": "img/singlestitch_thumb.jpg",
"url": "http://www.google.com",
"description": "an interactive 'kite' sketch based on a favorite letter[requires java]",
"smallwin": true
},
{
"img": "img/text3d_thumb2.jpg",
"url": "http://www.yahoo.com",
"description": "animated custom font design in 3d (featured on the 'processing' site)[requires java]",
"smallwin": true
},
{
"img": "img/jazzer_thumb.jpg",
"url": "http://flickr.com",
"description": "a 3d musician that 'plays along' with arbitrary audio tracks[req. javajsyn]",
"smallwin": true
}
]
}
testjson.html:
var cells = [];
$.getJSON("cells.json", function(json) {
$.each(json, function(i, lv_1) {
$.each(lv_1, function(j, lv_2) {
$.each(lv_2, function(k, lv_3) {
//console.log(k + ':' + lv_3 + '');
//console.log(JSON.parse(k + ':' + lv_3 + ''));
cells.push(k + ':' + lv_3 + '');
});
});
});
});
console.log(cells);
这是错误。
console.log(cells[0].url); // TypeError: cells[0] is undefined
我无法访问其中的元素。
附件是zip文件包。您可以使用Firefox或设置本地服务器进行测试。 https://www.dropbox.com/s/nmfq98s7raep92r/json%20test.zip?dl=0
谢谢!
http://jsfiddle.net/Lnjg57t8/错误:未定义 – 2014-12-02 12:28:30
这是从来没有去上班的你创建一个数组,而不是一个对象。如果你想要一个对象,你需要彻底改变你的逻辑 – 2014-12-02 12:28:52
谢谢!有没有教程呢?或者什么是阅读它的最佳方式?我只想读第一个'url',第一个'img',然后是第二个,等等。 – 2014-12-02 12:30:26