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('http://query.yahooapis.com/v1/publ...');
var count = responseObj.query.count;
console.log(count) // should be 1
How can I get a JavaScript object from this URL's JSON response?
If you want to do it in plain javascript, you can define a function like this:
And use it like this:
Note that
data
is an object, so you can access its attributes without having to parse it.You can use jQuery
.getJSON()
function:If you don't want to use jQuery you should look at this answer for pure JS solution: https://stackoverflow.com/a/2499647/1361042
Function:
usage:
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.
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.
Axios 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.
Or even just
axios(url)
is enough as aGET
request is the default.