0

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..

C. Cristi
  • 569
  • 1
  • 7
  • 21
  • 2
    That's not JSON. "Nothing really worked" is not a problem description. Is your code part of a web page? How are you running your code? – melpomene Feb 10 '19 at 13:56
  • Have you looked up NodeJS ? Filesystems in NodeJS? –  Feb 10 '19 at 13:58
  • @melpomene I am running my code in a ```script.js``` file that i attached on my html and css webpage – C. Cristi Feb 10 '19 at 13:58
  • OK, so it's running in a browser. Where is this JSON file located, on your web server or on the client machine (where the browser runs)? – melpomene Feb 10 '19 at 14:00
  • First, I wanted to test it locally in the same folder, but it would probably run on some webserver – C. Cristi Feb 10 '19 at 14:10
  • JavaScript code runs on the client. It cannot access files on some other machine (such as the web server). It can only send HTTP requests. – melpomene Feb 10 '19 at 14:15
  • See [Read local XML with JS](https://stackoverflow.com/questions/41279589/read-local-xml-with-js) – guest271314 Feb 10 '19 at 14:17
  • @melpomene okay, then if so, I somehow manage to get this "JSON file" somewhere on the web to receive and HTTP request and let javascript take that file, how would that be possible? – C. Cristi Feb 10 '19 at 14:22
  • Possible duplicate of [Loading local JSON file](https://stackoverflow.com/questions/7346563/loading-local-json-file) – MathKimRobin Feb 10 '19 at 14:38

2 Answers2

0

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();

Luis
  • 141
  • 1
  • 7
0

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

Tim S
  • 181
  • 1
  • 3
  • and what if my json file was from github what would I need to do extra? and what if I wanted to store that in a variable? – C. Cristi Feb 12 '19 at 14:44