Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

jquery - How would you import a JSON file into 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" },
            {"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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

  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/

  2. 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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...