如何在Javascript中将JSON文件用作对象数组

时间:2014-04-20 15:08:49

标签: javascript arrays json d3.js

我有一个使用对象数组的Javascript代码:

var words = [{"text":"This", "url":"http://google.com/"},
         {"text":"is", "url":"http://bing.com/"},
         {"text":"some", "url":"http://somewhere.com/"},
         {"text":"random", "url":"http://random.org/"},
         {"text":"text", "url":"http://text.com/"},
         {"text":"InCoMobi", "url":"http://incomobi.com/"},
         {"text":"Yahoo", "url":"http://yahoo.com/"}]

然后我在其余的代码中使用words,一切正常。

然后我将数据存储在JSON文件中,让我们调用文件“myfile.json”,其内容是:

{
"words": [
{"text":"This", "url":"http://google.com/"},
{"text":"is", "url":"http://bing.com/"},
{"text":"random", "url":"http://random.org/"},
{"text":"some", "url":"http://somewhere.com/"},
{"text":"text", "url":"http://text.com/"},
{"text":"InCoMobi", "url":"http://incomobi.com/"},
{"text":"Yahoo", "url":"http://yahoo.com/"}
]
}

我使用d3.json加载此文件:

d3.json("myfile.json", function(words) {
    console.log(words);  //Log output to console
});

然后我像以前一样使用words,现在我的代码不起作用了! 这两件事之间的区别是什么?如何修复加载文件的第二种方法?

2 个答案:

答案 0 :(得分:1)

两者之间的区别在于第一个是数组,而第二个是具有一个属性words的对象,其中包含第一个示例中的对象数组。

要将第二个转换为与第一个相同,只需执行:

d3.json("myfile.json", function(words) {

    words = words.words;
    console.log(words);  //Log output to console
});

答案 1 :(得分:1)

就像我在评论中说的那样“第一个单词是一个包含对象的数组,第二个单词是一个包含属性words的对象,它是一个对象数组”。

您想使用对象的属性,您可以像下面的示例一样执行此操作。

d3.json("myfile.json", function(result) {
    console.log(result.words); 
});