How to get JSON from URL in JavaScript? How to get JSON from URL in JavaScript? json json

How to get JSON from URL in JavaScript?

You can use jQuery .getJSON() function:

$.getJSON('', function(data) {    // JSON result in `data` variable});

If you don't want to use jQuery you should look at this answer for pure JS solution:

If you want to do it in plain javascript, you can define a function like this:

var getJSON = function(url, callback) {    var xhr = new XMLHttpRequest();'GET', url, true);    xhr.responseType = 'json';    xhr.onload = function() {      var status = xhr.status;      if (status === 200) {        callback(null, xhr.response);      } else {        callback(status, xhr.response);      }    };    xhr.send();};

And use it like this:

getJSON('',function(err, data) {  if (err !== null) {    alert('Something went wrong: ' + err);  } else {    alert('Your query count: ' + data.query.count);  }});

Note that data is an object, so you can access its attributes without having to parse it.

With Chrome, Firefox, Safari, Edge, and Webview you can natively use the fetch API which makes this a lot easier, and much more terse.

If you need support for IE or older browsers, you can also use the fetch polyfill.

let url = '';fetch(url).then(res => res.json()).then(out =>  console.log('Checkout this JSON! ', out)).catch(err => throw err);

MDN: Fetch API

Even though Node.js does not have this method built-in, you can use node-fetch which allows for the exact same implementation.