简体   繁体   中英

How to use a JSON file as an array of objects in Javascript

I have a Javascript code that uses an array of objects as:

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/"}]

Then I use words in the rest of code and everything works fine.

Then I store the data in a JSON file, lets call the file "myfile.json" its content is:

{
"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/"}
]
}

I load this file using d3.json as:

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

And then I use words the same as before, now my code does not work! What is the difference between the two things and how can I fix the second method that I load the file?

The difference between the two is that the first is an array, whereas the second is an object with one property words containing the the array of objects in the first example.

To convert the second to the same as the first simply do:

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

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

Like I said in my comment "the 1st words is an array which contains object, the 2nd words is an object that contains a property words which is an array of objects".

You want to use the words property of your object, you can do this like the example below.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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