【问题标题】:Transforming JSON array into JS array将 JSON 数组转换为 JS 数组
【发布时间】:2021-01-15 20:02:52
【问题描述】:

我有一个来自 JSON 文件的对象列表,需要将其存储为 JS 中的对象数组。

这将是我的 JSON:

   [
     {"id":"1","name":"abc"},
     {"id":"2","name":"pqr"},
     {"id":"3","name":"xyz"}
   ]

我需要它在 JS 中的一个变量中,像这样:

let data = [
     {"id":"1","name":"abc"},
     {"id":"2","name":"pqr"},
     {"id":"3","name":"xyz"}
   ];

我正在尝试使用 JQuery:

$.getJSON('json', function(data) {
    plates = $.parseJSON(data);
 });

但我收到以下错误:

VM464:1 Uncaught SyntaxError: 位置 1 处 JSON 中的意外标记 o 在 Function.parse [as parseJSON]

就我所见,我可能已经有了对象,不需要解析函数。是这个原因吗?

代码中的第二个问题

我在地图函数中使用数组:

data.map(data_item) => {
   //function
}

但我遇到了以下错误:

未捕获的类型错误:无法读取未定义的属性“地图”

为什么会这样?

【问题讨论】:

  • 您可能不需要解析 JSON。 $.getJSON 已经将数据作为 javascript 数组提供给您,而不是您需要解析的字符串

标签: javascript json dictionary parsing


【解决方案1】:

读取 JSON

jQuery.getJSON 发送一个 http 请求以从服务器检索 json。你应该只在需要从服务器(通过互联网)获取 json 时使用它,它不适合从文件中读取它。事实上,客户端 JavaScript 根本无法访问文件系统。这意味着,如果您的网络浏览器正在运行代码,则它无法读取计算机上的任何文件,除非您的用户专门使用 <input/> 元素上传文件。

因此,如果您希望用户能够上传 .json 文件,然后将其读入 javascript 对象,您可以在 html 中执行此操作:

<input type="file" id="upload">

然后在您的 javascript 中执行此操作:

document.getElementById('upload').addEventListener('change', readFile)
function readFile() {
    // This will run any time a file is selected or deselected.
    var files = this.files;
    if (files.length === 0) {
        console.log('No file is selected');
        return;
    }

    var reader = new FileReader();
    reader.onload = function(event) {
        // This is where you are given access to the file as a string. Convert the string to json...
        const fileText = event.target.result; // The text is stored in event.target.result
        const object = JSON.parse(event.target.result); // Parse the text as json
    };
    reader.readAsText(files[0]);
}

如果您确实想从服务器获取 JSON,那么您可以使用 $.getJSON,除非您之后不需要解析数据。您传递给getJSON 的第一个参数绝不应该是'json',它应该是您要检索的json 的URL:

$.getJSON('https://fakewebsite.com/api/data/get', function(data) {
    // here data is already json.
 });

未定义的'地图'

Uncaught TypeError: Cannot read property 'map' of undefined 您在data 上调用.map,而data 未定义。 data 需要是一个数组才能使用 map。如果您正确地将data 的值设置为数组,它将开始工作。

假设您按照我上面所说的进行了操作,并且您使用输入上传了一个文件并且该文件的文本是一个 JSON 数组,您现在可以这样做:

document.getElementById('upload').addEventListener('change', readFile)
function readFile() {
    // This will run any time a file is selected or deselected.
    var files = this.files;
    if (files.length === 0) {
        console.log('No file is selected');
        return;
    }

    var reader = new FileReader();
    reader.onload = function(event) {
        const fileText = event.target.result;
        const array = JSON.parse(event.target.result);
        array.map((data_item)=>{
            //function
        });
    };
    reader.readAsText(files[0]);
}

您的.map 函数的语法也不正确。相反,您需要像我上面所做的那样在内联函数周围使用一组括号:

data.map((data_item) => {
   //function
})

【讨论】:

  • 谢谢!真的解开了我的一些疑惑!我正在尝试将 JSON 作为来自服务器的响应,并使用其数据使用 map 函数将它们显示在 html 页面中。我的问题出在 map 函数中,我在 getJSON 之外使用了它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-06
  • 2014-01-23
  • 2014-10-10
  • 2011-08-02
  • 2014-01-30
相关资源
最近更新 更多