This URL returns JSON:
{ query: { count: 1, created: "2015-12-09T17:12:09Z", lang: "en-US", diagnostics: {}, ... } } I tried this, and it didn't work:
responseObj = readJsonFromUrl('); var count = responseObj.query.count; console.log(count) // should be 1 How can I get a JavaScript object from this URL's JSON response?
211 Answers
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.
3If you want to do it in plain javascript, you can define a function like this:
var getJSON = function(url, callback) { var xhr = new XMLHttpRequest(); xhr.open('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); Even though Node.js does not have this method built-in, you can use node-fetch which allows for the exact same implementation.
4ES8(2017) try
obj = await (await fetch(url)).json(); async function load() { let url = ' let obj = await (await fetch(url)).json(); console.log(obj); } load();you can handle errors by try-catch
async function load() { let url = ' let obj = null; try { obj = await (await fetch(url)).json(); } catch(e) { console.log('error'); } console.log(obj); } load();1Axios is a promise based HTTP client for the browser and node.js.
It offers automatic transforms for JSON data and it's the official recommendation from the Vue.js team when migrating from the 1.0 version which included a REST client by default.
Performing a
GETrequest// Make a request for a user with a given ID axios.get(') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
Or even just axios(url) is enough as a GET request is the default.
Define a function like:
fetchRestaurants(callback) { fetch(`) .then(response => response.json()) .then(json => callback(null, json.restaurants)) .catch(error => callback(error, null)) } Then use it like this:
fetchRestaurants((error, restaurants) => { if (error) console.log(error) else console.log(restaurants[0]) }); 3async function fetchDataAsync(url) { const response = await fetch(url); console.log(await response.json()); } fetchDataAsync('paste URL');2this morning, i also had the same doubt and now its cleared i had just used JSON with 'open-weather-map'() api and got data from the URL in the index.html file, the code looks like this:-
//got location var x = document.getElementById("demo"); if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(weatherdata); } else { x.innerHTML = "Geolocation is not supported by this browser."; } //fetch openweather map url with api key function weatherdata(position) { //put corrdinates to get weather data of that location fetch(') .then(response => response.json()) .then(data => { console.log(data); document.getElementById("demo").innerHTML = '<br>wind speed:-'+data.wind.speed + '<br>humidity :-'+data.main.humidity + '<br>temprature :-'+data.main.temp }); } <div></div>i had give api key openly because i had free subscription, just have a free subscriptions in beginning. you can find some good free api's and keys at "rapidapi.com"
as @DanAlboteanu answer in this page and some error corection of that javascript my suggested code is:
fetchRestaurants((error, data) => { if (error) console.log(error); else console.log(data) }); and fetchRestaurants method is(please replace your json url with {your url of json data}):
function fetchRestaurants(callback) { fetch("{your url of json data}") .then(response => response.json()) .then(json => callback(null, json)) .catch(error => callback(error, null)) } You can access JSON data by using fetch() in JavaScript
Update url parameter of fetch() with your url.
fetch(url) .then(function(response){ return response.json(); }) .then(function(data){ console.log(data); }) Hope It helps, it worked perfectly for me.
1//Resolved const fetchPromise1 = fetch(url); fetchPromise1.then(response => { console.log(response); }); //Pending const fetchPromise = fetch(url); console.log(fetchPromise); 2