Home > Web Front-end > JS Tutorial > body text

How to extract data from a JSON response in JavaScript?

Barbara Streisand
Release: 2024-10-28 03:32:02
Original
421 people have browsed it

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...
Copy after login

This URL returns a JSON response structured as follows:

{
  query: {
    count: 1,
    created: "2015-12-09T17:12:09Z",
    lang: "en-US",
    diagnostics: {},
    ...
  }
}
Copy after login

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
});
Copy after login

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
    }
};
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!