简体   繁体   中英

Read Json file into a variable

I want to read a JSON file into a variable. My JSON file would be named "questions.json" and will have this type of content:

{
      question: "Question 1?",
      answers: {
        a: "A",
        b: "B",
        c: "The Correct One"
      },
      correctAnswer: "c"
    },
    {
      question: "Question 2?",
      answers: {
        a: "A",
        b: "B",
        c: "The Correct One"
      },
      correctAnswer: "c"
}

I have tried many things to work this out, such as: loadStrings and then parse the string as a JSON type (told me that loadStrings is undefined), really everything i found on the web with reading local files in javascript and nothign really worked..

Similar question raised there: Loading local JSON file if you are using jquery, check the answer there, also reported here:

$.getJSON("questions.json", function(json) {
    console.log(json);
});

If you are just using javascript, check answer from xgqfrms using:

new XMLHttpRequest();

You could use the fetch api:

fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(JSON.stringify(myJson));
  });

There is a polyfill for older browsers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM