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 dodata.myObjectit says it’s undefined.
You need to parse the JSON before you can access it as an object…
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 .