JSON+Javascript/jQuery. How to import data from a json file and parse it?

前端 未结 7 2072
猫巷女王i
猫巷女王i 2021-01-31 19:12

If I have a JSON file named names.json with:

{\"employees\":[
    {\"firstName\":\"Anna\",\"lastName\":\"Meyers\"},
    {\"firstNam         


        
7条回答
  •  耶瑟儿~
    2021-01-31 19:43

    I know the answer was given a long time ago, but this result is showing in first position on google.

    However I don't want to use jquery, so in vanilla JS , I found this quick tutorial cleaner than senornestor answer (it also allow to load files depending on a variable) :

    function loadJSON(filelocation, callback) {   
    
      var xobj = new XMLHttpRequest();
      xobj.overrideMimeType("application/json");
      xobj.open('GET', filelocation, true); // Replace 'my_data' with the path to your file
      xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == "200") {
          // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
          callback(xobj.responseText);
        }
      };
      xobj.send(null);  
    }
    
    function init() {
      var location = "myfile.json";
      loadJSON(filelocation=location,  function(response) {
        // Parse JSON string into object
        loadedJSON = JSON.parse(response);
        console.log(loadedJSON.somethingsomething);
      });
    }
    
    init();
    

    and on your html file:

    ``
    

提交回复
热议问题