shirleytb
shirleytb

Reputation: 31

How to get JSON data from JSON file

I need to do an applet. This applet it is a stand reminder. I use a JSON file. I need to do a dropdown menu so I did this code in my JSON file :

`"questions": [
      {
        "key": "reminder",
        "label": "Choose the time",
        "help": "You can find the stock ticker on the web",
        "required": true,
        "order": 1,
        "controlType": "dropdown",
        "options":[10, 15, 20, 30, 40, 50, 60]
      }
    ],`

The options is a list in order to allow the user to choose when he want an alert. But I need to take the options in like an entry in my JS file, in order after to count down the time after with a function. Can you help me please to find how can I take options like an entry and to display it a JS file?

Upvotes: 0

Views: 217

Answers (1)

Unmitigated
Unmitigated

Reputation: 89517

You can use fetch to get the JSON file.

fetch("../yourFile.JSON").then(res => res.json()).then(data => {
   //do something with your JSON
});

fetch('https://jsonplaceholder.typicode.com/todos/1') .then(res => res.json()).then(json => {
    console.log(json);
});

Newer browsers support the responseType property of the XMLHttpRequest Object and you can set it to 'json' and then get the JSON response with response property of the XMLHttpRequest.

Note: responseType='json' is not supported by IE11

var req = new XMLHttpRequest;
req.responseType = 'json';
req.open('GET', "../yourFile.JSON", true);
req.onload  = function() {
   var json = req.response;
   // do something with your JSON
};
req.send(null);

var req = new XMLHttpRequest;
req.responseType = 'json';
req.open('GET', "https://jsonplaceholder.typicode.com/todos/1", true);
req.onload  = function() {
   var json = req.response;
   console.log(json);
   // do something with your JSON
};
req.send(null);

To support older browsers, you can use XMLHttpRequest and JSON.parse to convert the responseText to JSON.

var req = new XMLHttpRequest;
req.overrideMimeType("application/json");
req.open('GET', "../yourFile.JSON", true);
req.onload  = function() {
   var json = JSON.parse(req.responseText);
   //do something with your JSON
};
req.send(null);

var req = new XMLHttpRequest;
req.overrideMimeType("application/json");
req.open('GET', "https://jsonplaceholder.typicode.com/todos/1", true);
req.onload  = function() {
   var json = JSON.parse(req.responseText);
   console.log(json);
   //do something with your JSON
};
req.send(null);

Upvotes: 2

Related Questions