How to read an external local JSON file in JavaScript?

前端 未结 22 1940
醉酒成梦
醉酒成梦 2020-11-22 02:53

I have saved a JSON file in my local system and created a JavaScript file in order to read the JSON file and print data out. Here is the JSON file:

{"res         


        
相关标签:
22条回答
  • You could use D3 to handle the callback, and load the local JSON file data.json, as follows:

    <script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
    
    <script>
      d3.json("data.json", function(error, data) {
        if (error)
          throw error;
        console.log(data);
      });
    </script>
    
    0 讨论(0)
  • 2020-11-22 03:19

    If you could run a local web server (as Chris P suggested above), and if you could use jQuery, you could try http://api.jquery.com/jQuery.getJSON/

    0 讨论(0)
  • 2020-11-22 03:20

    Depending on your browser, you may access to your local files. But this may not work for all the users of your app.

    To do this, you can try the instructions from here: http://www.html5rocks.com/en/tutorials/file/dndfiles/

    Once your file is loaded, you can retrieve the data using:

    var jsonData = JSON.parse(theTextContentOfMyFile);
    
    0 讨论(0)
  • 2020-11-22 03:23

    Using the Fetch API is the easiest solution:

    fetch("test.json")
      .then(response => response.json())
      .then(json => console.log(json));
    

    It works perfect in Firefox, but in Chrome you have to customize security setting.

    0 讨论(0)
提交回复
热议问题