How to read an external local JSON file in JavaScript?

前端 未结 22 1941
醉酒成梦
醉酒成梦 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条回答
  • 2020-11-22 03:14

    I liked what Stano/Meetar commented above. I use it to read .json files. I have expanded their examples using Promise. Here is the plunker for the same. https://plnkr.co/edit/PaNhe1XizWZ7C0r3ZVQx?p=preview

    function readTextFile(file, callback) {
        var rawFile = new XMLHttpRequest();
        rawFile.overrideMimeType("application/json");
        rawFile.open("GET", file, true);
        rawFile.onreadystatechange = function() {
            if (rawFile.readyState === 4 && rawFile.status == "200") {
                callback(rawFile.responseText);
            }
        }
        rawFile.send(null);
    }
    
    //usage:
    // readTextFile("DATA.json", function(text){
    //     var data = JSON.parse(text);
    //     console.log(data); 
    // });
    
    
    var task1 = function (){
      return new Promise (function(resolve, reject){
        readTextFile("DATA.json", function(text){
        var data = JSON.parse(text);
        console.log('task1 called');
        console.log(data);
        resolve('task1 came back');
        }); 
      });
    };
    
    var task2 = function (){
      return new Promise (function(resolve, reject){
        readTextFile("DATA2.json", function(text){
        var data2 = JSON.parse(text);
        console.log('task2 called');
        console.log(data2);
        resolve('task2 came back');
        });
      });
    }
    
    Promise.race([task1(), task2()])
           .then(function(fromResolve){
              console.log(fromResolve); 
           });
    

    The reading of JSON can be moved into another function, for DRY; but the example here is more of showcasing how to use promises.

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

    You can use d3.js to import JSON files. Just call d3 on your html body:

    <script src="https://d3js.org/d3.v5.min.js"></script>
    

    Then put this on your js scripts:

      d3.json("test.json").then(function(data_json) {
             //do your stuff
      })
    
    0 讨论(0)
  • 2020-11-22 03:15

    I took Stano's excellent answer and wrapped it in a promise. This might be useful if you don't have an option like node or webpack to fall back on to load a json file from the file system:

    // wrapped XMLHttpRequest in a promise
    const readFileP = (file, options = {method:'get'}) => 
      new Promise((resolve, reject) => {
        let request = new XMLHttpRequest();
        request.onload = resolve;
        request.onerror = reject;
        request.overrideMimeType("application/json");
        request.open(options.method, file, true);
        request.onreadystatechange = () => {
            if (request.readyState === 4 && request.status === "200") {
                resolve(request.responseText);
            }
        };
        request.send(null);
    });
    

    You can call it like this:

    readFileP('<path to file>')
        .then(d => {
          '<do something with the response data in d.srcElement.response>'
        });
    
    0 讨论(0)
  • 2020-11-22 03:16


    As many people mentioned before, this doesn't work using an AJAX call. However, there's a way around it. Using the input element, you can select your file.

    The file selected (.json) need to have this structure:

    [
        {"key": "value"},
        {"key2": "value2"},
        ...
        {"keyn": "valuen"},
    ]
    


    <input type="file" id="get_the_file">
    

    Then you can read the file using JS with FileReader():

    document.getElementById("get_the_file").addEventListener("change", function() {
      var file_to_read = document.getElementById("get_the_file").files[0];
      var fileread = new FileReader();
      fileread.onload = function(e) {
        var content = e.target.result;
        // console.log(content);
        var intern = JSON.parse(content); // Array of Objects.
        console.log(intern); // You can index every object
      };
      fileread.readAsText(file_to_read);
    });
    
    0 讨论(0)
  • 2020-11-22 03:16

    If you are using local files, why not just packade the data as a js object?

    data.js

    MyData = { resource:"A",literals:["B","C","D"]}
    

    No XMLHttpRequests, no parsing, just use MyData.resource directly

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

    So, if you are planning to go with "Apache Tomcat" for hosting your JSON file,

    1> After starting up the server, verify that your Apache Tomcat is up and running by going to this url: "localhost:8080" -



    2> Next, go to the "webapps" folder - "C:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps". And, create a project folder or copy your project folder.




    3> Paste your json file over there.



    4> And that's it. You are done! Just go to - "http://localhost:8080/$project_name$/$jsonFile_name$.json"

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