Home  >  Article  >  Web Front-end  >  How to extract data from a JSON response in JavaScript?

How to extract data from a JSON response in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-10-28 03:32:02422browse

How to extract data from a JSON response in JavaScript?

How to Parse JSON Response from a URL in JavaScript

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.

Using jQuery's .getJSON() Function

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
});

Using Pure JavaScript

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!

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