简体   繁体   中英

How to get data from JSON response?

I am using plain JavaScript on my project. How can I get the value of the following example with the category? I need to detect whether it comes back true or false.

{
    "category": "true"
}

I can get the entire object, but I just want to pull out the value of category.


from comment...

The JSON data is returned from the server based on a form submission. It keeps saying myObject is undefined. How can do I pass this so my JavaScript can read the response?

from comment...

I can get myObject using this: if (form.XHR.status === 200) {var data = form.XHR.response;} , but if I try to do data.myObject it says it's undefined.

You need to parse the JSON before you can access it as an object...

if (form.XHR.status === 200) {
    var data = form.XHR.response;

    var parsed = JSON.parse(data);

    alert(parsed.category);
}

Why is this needed? It's because JSON is not JavaScript . The two terms are not synonymous.

JSON is a textual data interchange format. It needs to be parsed into the data structures of whatever language it's been given to. In your case, the language is JavaScript, so you need to parse it into JavaScript data.

When it is received form the xhr response, it is received in the form in which all textual data is handled in JavaScript. That is as a string . As a string, you can't directly access the values represented.

JavaScript has a built in parser called JSON.parse . This was used in the example above to do the necessary conversion.

Some older browsers don't support JSON.parse . If you're supporting those browsers, you can find a JavaScript parser at http://json.org .

First of all you need a variable to refer it:

var obj = {
    "category": "true"
};

Then can you say eg:

alert(obj.category);
var myObject = { "category": "true"};

alert (myObject.category);

But you likely want:

var myObject = { "category": true};

...if you're going to be testing for true/false:

if (myObject.category) {
    // category is true, so do your stuff here.
}

You can access json object data using '.' or [key] like this :

var obj = {
    "category": "true"
};
console.log(obj.category);   
// Or
console.log(obj["category"]);

Here is the DEMO

For anyone who arrives here banging their head against the wall, make sure to see if you need to access a parent object which wraps all the delivered data:

console.log(response['id'])

may not work, because a parent entity must be accessed first:

console.log(response.session['id'])

If you console log your response and it is wrapped in {} you probably need to do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM