Home >Web Front-end >JS Tutorial >How to Extract JSON Data from a URL Using JavaScript?

How to Extract JSON Data from a URL Using JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-10-27 20:46:30516browse

How to Extract JSON Data from a URL Using JavaScript?

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&amp;format=json&amp;diagnostics=true&amp;env=store://datatables.org/alltableswithkeys&amp;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&amp;format=json&amp;diagnostics=true&amp;env=store://datatables.org/alltableswithkeys&amp;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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn