Many web services provide their responses in JSON format, making them easily integrated with JavaScript applications. However, accessing data from a JSON response can be challenging for beginners.
Consider this example URL:
http://query.yahooapis.com/v1/publ...
This URL returns a JSON response structured as follows:
{ query: { count: 1, created: "2015-12-09T17:12:09Z", lang: "en-US", diagnostics: {}, ... } }
To parse this JSON response and create a JavaScript object, several options are available.
jQuery provides a convenient function called .getJSON() for fetching JSON data from a URL. By specifying the URL and a callback function, you can handle the response:
$.getJSON('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', function(data) { // JSON result in `data` variable });
An alternative to jQuery is to use pure JavaScript to handle the JSON response. The XMLHttpRequest object can be used to make a GET request to the URL:
var xhr = new XMLHttpRequest(); xhr.open('GET', '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'); xhr.send(); xhr.onload = function() { if (xhr.status == 200) { var responseObj = JSON.parse(xhr.responseText); // JSON result in `responseObj` variable } };
The above is the detailed content of How to extract data from a JSON response in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!