How would you import a JSON file into JavaScript?

ajax, javascript, jquery, json

Solution

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)

Problem

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.

Original source

Related problems