I’m trying to fetch JSON data from this URL:
http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback
The response returns a JSON object like this:
{
"query": {
"count": 1,
"created": "2015-12-09T17:12:09Z",
"lang": "en-US",
"diagnostics": {}
}
}
I tried using readJsonFromUrl('http://query.yahooapis.com/v1/publ...');
but it didn’t work.
How can I correctly retrieve and parse the JSON from this URL in JavaScript?
You can fetch() method with async/await :
async function getData() {
const response = await fetch('https://your-url.com');
const json = await response.json();
console.log(json);
}
getData();
The fetch()
gets the response from the URL. The await response.json()
parses it into a JavaScript object. It works best inside an async
function.
fetch()
with .then()
for older codebases is useful if you’re not using async/await. It’s clean and handles errors with .catch()
.
fetch('https://your-url.com')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
If jQuery is already loaded, you can use its shorthand AJAX methods for convenient data fetching.
$.getJSON('https://your-url.com', function(data) {
console.log(data);
});
$.getJSON()
is a shorthand AJAX call in jQuery that handles JSON parsing automatically. Use only if your project includes jQuery.