I want to parse a JSON string in JavaScript. The response is something like
var response = '{"result":true,"count":1}';
How can I get the values result
and count
from this?
I want to parse a JSON string in JavaScript. The response is something like
var response = '{"result":true,"count":1}';
How can I get the values result
and count
from this?
The standard way to parse JSON in JavaScript is
JSON.parse()
The
JSON
API was introduced with ES5 (2011) and has since been implemented in >99% of browsers by market share, and Node.js. Its usage is simple:The only time you won't be able to use
JSON.parse()
is if you are programming for an ancient browser, such as IE 7 (2006), IE 6 (2001), Firefox 3 (2008), Safari 3.x (2009), etc. Alternatively, you may be in an esoteric JavaScript environment that doesn't include the standard APIs. In these cases, use json2.js, the reference implementation of JSON written by Douglas Crockford, the inventor of JSON. That library will provide an implementation ofJSON.parse()
.When processing extremely large JSON files,
JSON.parse()
may choke because of its synchronous nature and design. To resolve this, the JSON website recommends third-party libraries such as Oboe.js and clarinet, which provide streaming JSON parsing.jQuery once had a
$.parseJSON()
function, but it was deprecated with jQuery 3.0. In any case, for a long time it was nothing more than a wrapper aroundJSON.parse()
.JSON.parse() converts any JSON String passed into the function, to a JSON object.
For better understanding, press F12 to open the Inspect Element of your browser, and go to the console to write the following commands:
Now run the command:
You'll get output as Object {result: true, count: 1}.
In order to use that object, you can assign it to the variable, let's say
obj
:Now by using
obj
and the dot(.) operator you can access properties of the JSON Object.Try to run the command
If you pass a string variable (a well-formed JSON string) to JSON.parse from MVC @Viewbag that has doublequote, '"', as quotes, you need to process it before JSON.parse (
jsonstring
)As mentioned by numerous others, most browsers support
JSON.parse
andJSON.stringify
.Now, I'd also like to add that if you are using AngularJS (which I highly recommend), then it also provides the functionality that you require:
I just wanted to add the stuff about AngularJS to provide another option. NOTE that AngularJS doesn't officially support Internet Explorer 8 (and older versions, for that matter), though through experience most of the stuff seems to work pretty well.
An easy way to do it:
I thought
JSON.parse(myObject)
would work. But depending on the browsers, it might be worth usingeval('('+myObject+')')
. The only issue I can recommend watching out for is the multi-level list in JSON.