How to read an external local JSON file in JavaScript?

前端 未结 22 1971
醉酒成梦
醉酒成梦 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: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('')
        .then(d => {
          ''
        });
    

提交回复
热议问题