1701

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?

Taryn
  • 224,125
  • 52
  • 341
  • 389
  • 1
    var json = '{"result":true,"count":1}', obj = JSON.parse(json); console.log(obj.count); // if use in nodejs then use console – Shekhar Tyagi Dec 19 '16 at 13:06

16 Answers16

1999

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().

Not A Bot
  • 2,220
  • 2
  • 10
  • 24
Andy E
  • 311,406
  • 78
  • 462
  • 440
  • i think JSON.parse not working in IE ?? – Marwan Nov 16 '11 at 09:26
  • 36
    @Marwan: IE 8+ supports `JSON.parse()`. For IE 6, 7 and other older browsers, you can use the json2.js I linked to from my post. Alternatively, but less securely, you can use `eval`. – Andy E Nov 16 '11 at 09:46
  • @AndyE, you can also use jQuery too (in case it already included jQuery, he doesn't need an extra library.) – Derek 朕會功夫 May 08 '12 at 23:25
  • 10
    Unless he also needs `JSON.stringify()` – ThiefMaster May 09 '12 at 11:19
  • 17
    Note to reviewers: please thoroughly check peer edits before allowing them, as your actions may cause unwanted side-effects for users copying and pasting code from answers. – Andy E Apr 02 '13 at 09:42
  • Shouldn't you just stick with $.parseJSON? – chaz Aug 05 '13 at 14:47
  • 1
    If you implement the [JSON3](http://bestiejs.github.io/json3/) library this will fill in the gaps in browsers that do not natively support JavaScript, such as IE7 – Liam Oct 22 '13 at 09:34
  • 12
    It's not necessary to check for native support first and then fall back to jQuery. jQuery 1.10 tries `JSON.parse` first, then the own implementation. jQuery 2.x is directly calling `JSON.parse` without checking or fallback. – Jasha Nov 04 '13 at 15:29
  • 4
    Browser support details: [Can I use JSON parsing](http://caniuse.com/json) – Peter V. Mørch Jan 07 '14 at 10:11
  • eval() will also parse json to javascript objects. But eval() function can compile and execute any javascripts too. So, if uses eval(), there is a potential security issue. – Janaka R Rajapaksha May 20 '14 at 16:07
  • 2
    @AndyE, what if the JSON is `'{"1":{"result":"true","count":"1"},"2":{"result":"false","count":"2"}}'` instead ? We'll have a [Object object] in output. How to do it in this case ? – hacks4life Jun 19 '14 at 13:55
  • Since this post is one of the most popular ones on JSON in SO, can someone please include a thorough guideline to give an understanding on JSON escape characters as well? – Baz Guvenkaya Oct 01 '15 at 02:47
  • I'm going to be that guy who posts on a 5-year-old answer...If you execute `obj = JSON && JSON.parse(json) || $.parseJSON(json)`, and the `json` string represents a falsy value, like `0` or `null`, then both `JSON.parse` and `$.parseJSON` will fire, because the `JSON && JSON.parse(json)` part evaluates to a falsy value. So it's technically not quite the best all around performance, but it would of course be a negligible difference. – Joe Enos Oct 14 '16 at 22:36
103

WARNING!

This answer stems from an ancient era of JavaScript programming during which there was no builtin way to parse JSON. The advice given here is no longer applicable and probably dangerous. From a modern perspective, parsing JSON by involving jQuery or calling eval() is nonsense. Unless you need to support IE 7 or Firefox 3.0, the correct way to parse JSON is JSON.parse().

First of all, you have to make sure that the JSON code is valid.

After that, I would recommend using a JavaScript library such as jQuery or Prototype if you can because these things are handled well in those libraries.

On the other hand, if you don't want to use a library and you can vouch for the validity of the JSON object, I would simply wrap the string in an anonymous function and use the eval function.

This is not recommended if you are getting the JSON object from another source that isn't absolutely trusted because the eval function allows for renegade code if you will.

Here is an example of using the eval function:

var strJSON = '{"result":true,"count":1}';
var objJSON = eval("(function(){return " + strJSON + ";})()");
alert(objJSON.result);
alert(objJSON.count);

If you control what browser is being used or you are not worried people with an older browser, you can always use the JSON.parse method.

This is really the ideal solution for the future.

Community
  • 1
  • 1
Clarence Fredericks
  • 1,207
  • 1
  • 7
  • 4
  • Great man! I couldn't import the JSON lib, because it conflicted with other libs – Tahir Malik Oct 01 '12 at 16:09
  • 27
    eval() is OK to fulfill a job, while it may compile and execute any Javascript program, so there can be [security issues](http://www.json.org/js.html). I think JSON.parse() is a better choice. – ray6080 Sep 10 '13 at 11:58
  • 4
    *Note for passerby:* here's a good online tool to check if your JSON string is valid: http://jsonlint.com – Amal Murali Jul 30 '14 at 15:40
  • 17
    NO, NO, NO!!! Using eval to evaluate JSON is a really dangerous idea. Are you 100% certain there is no possibility that someone could inject their own code into your string? – Charles Jul 21 '15 at 18:07
  • 4
    Worth mentioning that there's no such a thing as a _JSON object_. – Jezen Thomas Sep 02 '16 at 15:29
62

If you are getting this from an outside site it might be helpful to use jQuery's getJSON. If it's a list you can iterate through it with $.each

$.getJSON(url, function (json) {
    alert(json.result);
    $.each(json.list, function (i, fb) {
        alert(fb.result);
    });
});
K.Dᴀᴠɪs
  • 9,384
  • 11
  • 31
  • 39
milestyle
  • 911
  • 7
  • 14
39

If you want to use JSON 3 for older browsers, you can load it conditionally with:

<script>
    window.JSON || 
    document.write('<script src="//cdnjs.cloudflare.com/ajax/libs/json3/3.2.4/json3.min.js"><\/scr'+'ipt>');
</script>

Now the standard window.JSON object is available to you no matter what browser a client is running.

K.Dᴀᴠɪs
  • 9,384
  • 11
  • 31
  • 39
huwiler
  • 705
  • 8
  • 9
  • 1
    It is available to you *after `json3.min.js` has finished loading*. This doesn't give you a callback when it is available. So your code may work today, but won't work on wednesday when cdnjs.cloudflare.com is suddenly slower than usual or the network is loaded or one of 10000 other reasons. [RequireJS](http://requirejs.org/) instead. – Peter V. Mørch Jan 07 '14 at 10:14
  • 5
    Peter, that is not correct. Both the loading of external scripts and document.write are synchronous activities, so all scripts placed after will wait until it's loaded before executing. For loading just JSON3, this is a fine approach. RequireJS would come in handy if your project grew in complexity and had to load scripts with complex dependency relationships. Just remember that document.write will block page rendering, so place it at the bottom of your markup. – huwiler Jan 29 '14 at 03:18
  • 3
    Sorry; I think you're right. Please disregard my comment as bogus. – Peter V. Mørch Jan 30 '14 at 04:04
  • Peter, your 1st comment is informative & useful (good to have that warning), just not applicable in 100% of cases. For a slightly more stable & faster CDN, you can use [jsDelivr](http://www.jsdelivr.com/#!json3): `//cdn.jsdelivr.net/json3/latest/json3.min.js` – tomByrer Mar 10 '14 at 01:43
37

The following example will make it clear:

let contactJSON = '{"name":"John Doe","age":"11"}';
let contact = JSON.parse(contactJSON);
console.log(contact.name + ", " + contact.age);

// Output: John Doe, 11
MultiplyByZer0
  • 4,341
  • 3
  • 27
  • 46
Joke_Sense10
  • 4,893
  • 2
  • 15
  • 20
32

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)

    var jsonstring = '@ViewBag.jsonstring';
    jsonstring = jsonstring.replace(/&quot;/g, '"');  
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Jenna Leaf
  • 1,827
  • 17
  • 24
  • What do you mean with that? Why do you post an answer for an ancient question? – kay Oct 22 '14 at 16:32
  • 7
    What they said in the previous answers do not help the case that if the parameter value has double quotes in the string. It needs to be replaced globally with a real double quote !! I find out in a hard way just to share in case somebody has the same problem – Jenna Leaf Oct 22 '14 at 16:40
  • 5
    Kay: I clarified my posting right now, this is the first time I've ever tried to help. Please look at the posting again. You know that quote thing output from server page is a real problem to JSON.parse(). – Jenna Leaf Oct 22 '14 at 17:18
29

You can either use the eval function as in some other answers. (Don't forget the extra braces.) You will know why when you dig deeper), or simply use the jQuery function parseJSON:

var response = '{"result":true , "count":1}'; 
var parsedJSON = $.parseJSON(response);

OR

You can use this below code.

var response = '{"result":true , "count":1}';
var jsonObject = JSON.parse(response);

And you can access the fields using jsonObject.result and jsonObject.count.

Update:

If your output is undefined then you need to follow THIS answer. Maybe your json string has an array format. You need to access the json object properties like this

var response = '[{"result":true , "count":1}]'; // <~ Array with [] tag
var jsonObject = JSON.parse(response);
console.log(jsonObject[0].result); //Output true
console.log(jsonObject[0].count); //Output 1
nandur93
  • 105
  • 8
Teja
  • 1,166
  • 11
  • 25
26

The easiest way using parse() method:

var response = '{"a":true,"b":1}';
var JsonObject= JSON.parse(response);

this is an example of how to get values:

var myResponseResult = JsonObject.a;
var myResponseCount = JsonObject.b;
Jorgesys
  • 114,263
  • 22
  • 306
  • 247
24

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:

var response = '{"result":true,"count":1}'; // Sample JSON object (string form)
JSON.parse(response); // Converts passed string to a JSON object.

Now run the command:

console.log(JSON.parse(response));

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:

var obj = JSON.parse(response);

Now by using obj and the dot(.) operator you can access properties of the JSON Object.

Try to run the command

console.log(obj.result);
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Pushkar Kathuria
  • 321
  • 2
  • 16
22

Without using a library you can use eval - the only time you should use. It's safer to use a library though.

eg...

var response = '{"result":true , "count":1}';

var parsedJSON = eval('('+response+')');

var result=parsedJSON.result;
var count=parsedJSON.count;

alert('result:'+result+' count:'+count);
El Ronnoco
  • 11,001
  • 5
  • 34
  • 63
21

If you like

var response = '{"result":true,"count":1}';
var JsonObject= JSON.parse(response);

you can access the JSON elements by JsonObject with (.) dot:

JsonObject.result;
JsonObject.count;
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
user5676965418
  • 241
  • 2
  • 3
13

I thought JSON.parse(myObject) would work. But depending on the browsers, it might be worth using eval('('+myObject+')'). The only issue I can recommend watching out for is the multi-level list in JSON.

ha9u63ar
  • 4,811
  • 7
  • 54
  • 80
  • 3
    eval() can compile and execute any javascript too. so you are at a potential security issue if using eval(). but json parser will recognize only json strings and compile them into javascript objects. – Janaka R Rajapaksha May 20 '14 at 16:13
10

An easy way to do it:

var data = '{"result":true,"count":1}';
var json = eval("[" +data+ "]")[0]; // ;)
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
yassine
  • 157
  • 1
  • 2
8

As mentioned by numerous others, most browsers support JSON.parse and JSON.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:

var myJson = '{"result": true, "count": 1}';
var obj = angular.fromJson(myJson);//equivalent to JSON.parse(myJson)
var backToJson = angular.toJson(obj);//equivalent to JSON.stringify(obj)

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
user2359695
  • 697
  • 7
  • 7
8

If you use Dojo Toolkit:

require(["dojo/json"], function(JSON){
    JSON.parse('{"hello":"world"}', true);
});
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Brendon-Van-Heyzen
  • 2,453
  • 2
  • 26
  • 23
  • var j='[{ "name":"John", "age":30, "city":"New York"}, { "name":"George", "age":48, "city":"Kutaisi"}]'; var obj = JSON.parse(j); alert(obj.length); for(var i=0; i – GGSoft Jan 02 '18 at 20:05
6

If you use jQuery, it is simple:

var response = '{"result":true,"count":1}';
var obj = $.parseJSON(response);
alert(obj.result); //true
alert(obj.count); //1
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
legendJSLC
  • 407
  • 4
  • 7