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?
Answer
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:
const json = '{ "fruit": "pineapple", "fingers": 10 }';
const obj = JSON.parse(json);
console.log(obj.fruit, obj.fingers);
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 of JSON.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 around JSON.parse()
.
No comments:
Post a Comment