导入JSON文件的JavaScript [英] Import JSON file to javascript

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

问题描述

我的JSON文件

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

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

和我的JavaScript文件,其中有

and I have javascript file which have

var treeData ={};

我要导入JSON文件,JavaScript和有导致这样的JavaScript文件中

I want to import JSON file to javascript and have result like this in javascript file

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

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

我已经试过了很多code,但它不能正常工作。

I have tried alot of code but it doesn't work.

感谢帮助

推荐答案

解析该文件中像这样的内容:

Parse the content of the file like this:

var treeData = JSON.parse(fileContent);

您没有说明如何获取该文件,但可以加载它关闭使用简单XMLHtt prequest您的服务器。下面是一个有用的资源: 使用XMLHtt prequest

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()。此功能只能在现有的字符串转换成Java对象(如果内容是有效的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(如图所示)的变量。不能使用本地文件路径,由于安全方面的原因。设置一个本地服务器运行在您的网页,如免费的轻质猫鼬web服务器。这将让你点了根到本地文件夹中,然后使用加载页面的http://本地主机/

  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()功能。上面的例子显示了整个过程。只需要用实际的人在你的code链接。

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天全站免登陆