简体   繁体   中英

How do I convert JSON from a file into an array in JavaScript?

I am having trouble parsing JSON. The JSON is properly getting read (as seen in the console), however, I am unable to get the array to save any of the data. I have looked at similar questions but none of them seemed to help my problem. Thank you in advance for any help.

function getArray(){
    return $.getJSON('testJSON.json');
}

getArray().done(function(json) {
    $.each(json, function(key, val) {

            words.push(key);
        console.log(key);
    });
});

JSON.parse() seems to be what you're looking for. I'll show how I used it in my project:

I used the jQuery get function to make a HTTP request, then I used JSON.stringify to convert the returned data to a string. I'm not sure if that was necessary for parsing it, or whether I done that so I could store the data in the HTML5 LocalStorage.

eg

    var treasureHuntString = JSON.stringify(data)
    var treasureHunt = JSON.parse(treasureHuntString);

And from thereafter, I could access all the properties within the treasureHunt object. I also made use of browser debugging to be able to see the structure of the object, as it was a little different to what I had expected.

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