如何将JSON从文件转换为JavaScript数组?

时间:2022-10-30 13:15:54

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.

解析JSON有困难。JSON正在正确地读取(如控制台中所示),但是,我无法让数组保存任何数据。我也遇到过类似的问题,但似乎没有一个对我的问题有帮助。事先谢谢你的帮助。

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

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

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

1 个解决方案

#1


0  

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

parse()似乎是您正在寻找的。我将展示我如何在我的项目中使用它:

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.

我使用jQuery get函数发出HTTP请求,然后使用JSON。stringify将返回的数据转换为字符串。我不确定是否需要解析它,或者是否需要这样做,以便可以将数据存储在HTML5 LocalStorage中。

e.g.

如。

    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.

从那以后,我就可以进入宝库中所有的属性。我还使用浏览器调试来查看对象的结构,因为它与我预期的有点不同。

#1


0  

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

parse()似乎是您正在寻找的。我将展示我如何在我的项目中使用它:

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.

我使用jQuery get函数发出HTTP请求,然后使用JSON。stringify将返回的数据转换为字符串。我不确定是否需要解析它,或者是否需要这样做,以便可以将数据存储在HTML5 LocalStorage中。

e.g.

如。

    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.

从那以后,我就可以进入宝库中所有的属性。我还使用浏览器调试来查看对象的结构,因为它与我预期的有点不同。