Retrieving JSON Data from a URL Using JavaScript
This article addresses the issue of extracting JSON data from a specific URL. The provided URL returns JSON in the following format:
<code class="json">{ query: { count: 1, created: "2015-12-09T17:12:09Z", lang: "en-US", diagnostics: {}, ... } }</code>
Attempts to access the JSON object using the following code were unsuccessful:
<code class="js">responseObj = readJsonFromUrl('http://query.yahooapis.com/v1/publ...'); var count = responseObj.query.count; console.log(count) // should be 1</code>
Solution:
To obtain a JavaScript object from the URL's JSON response, one can utilize jQuery's .getJSON() function:
<code class="js">$.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 });</code>
Alternatively, for a pure JavaScript solution, consider the following answer:
<code class="js">// Create a new XMLHttpRequest object var xhr = new XMLHttpRequest(); // Open a GET request to the specified URL 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&callback', true); // Set the response type to JSON xhr.responseType = 'json'; // Send the request xhr.send(); // Handle the response xhr.onload = function() { if (xhr.status === 200) { // The request was successful var data = xhr.response; // Access the JSON data as needed console.log(data.query.count); } else { // The request failed console.log('Error: ' + xhr.status); } };</code>
The above is the detailed content of How to Extract JSON Data from a URL Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!