import引入json文件_如何将JSON文件导入JavaScript?
I have a JSON file with content{"name" : "Conrad", "info" : "tst", "children" : [{"name" : "Rick" },{"name" : "Lynn" },{"name" : "John", "children": [{"name" : "Dave", "children": [{"name" : "Dave" },
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" }
]}
]};
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);
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);
}
Update based on comments below:
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).
You need to:
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/
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: if you wanted a jQuery solution remember to tag your question with the jQuery tag)
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐

所有评论(0)