如何将JSON文件导入JavaScript? [英] How would you import a JSON file into JavaScript?

查看:2022
本文介绍了如何将JSON文件导入JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个内容的JSON文件

I have a JSON file with content

{"name" : "Conrad", "info" : "tst", "children" : [
    {"name" : "Rick" },
    {"name" : "Lynn" },
    {"name" : "John", "children": [
        {"name" : "Dave", "children": [
            {"name" : "Dave" },
            {"name" : "Chris" }      
        ]},
        {"name" : "Chris" }
    ]}
  ]};

我想在JavaScript文件中导入此JSON文件数据,并得到最终结果,如

I want to import this JSON file data inside a JavaScript file and have the final result like

var treeData ={"name" : "Conrad", "info" : "tst", "children" : [
        {"name" : "Rick" },
        {"name" : "Lynn" },
        {"name" : "John", "children": [
                {"name" : "Dave", "children": [
                {"name" : "Dave" },
                {"name" : "Chris" }

         ] },
                {"name" : "Chris" }
         ]}
  ]};

我尝试了很多代码示例,但没有一个有效。

I've tried many code samples but none have worked.

推荐答案

解析文件的内容,如下所示:

Parse the content of the file like this:

var treeData = JSON.parse(fileContent);

您没有描述如何获取文件,但可以使用以下方法将其从服务器上加载简单的XMLHttpRequest。这是一个有用的资源:
使用XMLHttpRequest

You don't describe how you obtain the file but you can load it off of your server using a simple XMLHttpRequest. Here is a useful resource for that: Using XMLHttpRequest

从包含修改的链接中摘录:

Excerpt from the link with modifications:

var treeData;

var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "yourFile.txt", true);
oReq.send();

function reqListener(e) {
    treeData = JSON.parse(this.responseText);
}

根据以下评论更新

您无法使用 JSON.parse() 加载文件。此函数只能将现有字符串转换为对象(如果内容是有效的JSON格式)。

You cannot load a file with JSON.parse(). This function is only able to convert an existing string into an object (if content is in valid JSON format).

您需要:


  1. 使用例如AJAX将文件从服务器加载到变量(如图所示)。出于安全原因,您无法使用本地文件路径。设置本地服务器以运行您的页面,例如免费的轻量级 Mongoose Web服务器 。这将允许您将根指向本地文件夹,然后使用 http:// localhost /

  1. Load the file from your server to a variable using for example AJAX (as shown). You cannot use a local file path due to security reasons. Set up a local server to run your page in such as the free light-weight Mongoose web server. This will let you point the root to your local folder, then load your page using http://localhost/

加载文件后,您可以将内容传递给 JSON.parse()函数。上面的例子显示了整个过程。只需用代码中的实际链接替换链接。

When file has been loaded you can pass the content to the JSON.parse() function. The example above show the whole process. Just replace links with actual ones in your code.

(PS:如果你想要一个jQuery解决方案,请记得标记你的用jQuery标签提问)

(PS: if you wanted a jQuery solution remember to tag your question with the jQuery tag)

这篇关于如何将JSON文件导入JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆