Parse JSON in JavaScript?

JavascriptJsonParsing

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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);
    });
});

Solution 4 - Javascript

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.

Solution 5 - Javascript

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

Solution 6 - Javascript

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, '"');  

Solution 7 - Javascript

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

Solution 8 - Javascript

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;

Solution 9 - Javascript

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);

Solution 10 - Javascript

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);

Solution 11 - Javascript

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;

Solution 12 - Javascript

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.

Solution 13 - Javascript

An easy way to do it:

var data = '{"result":true,"count":1}';
var json = eval("[" +data+ "]")[0]; // ;)

Solution 14 - Javascript

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.

Solution 15 - Javascript

If you use Dojo Toolkit:

require(["dojo/json"], function(JSON){
    JSON.parse('{"hello":"world"}', true);
});

Solution 16 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser605334View Question on Stackoverflow
Solution 1 - JavascriptAndy EView Answer on Stackoverflow
Solution 2 - JavascriptClarence FredericksView Answer on Stackoverflow
Solution 3 - JavascriptmilestyleView Answer on Stackoverflow
Solution 4 - JavascripthuwilerView Answer on Stackoverflow
Solution 5 - JavascriptJoke_Sense10View Answer on Stackoverflow
Solution 6 - JavascriptJenna LeafView Answer on Stackoverflow
Solution 7 - JavascriptTejaView Answer on Stackoverflow
Solution 8 - JavascriptJorgesysView Answer on Stackoverflow
Solution 9 - JavascriptPushkar KathuriaView Answer on Stackoverflow
Solution 10 - JavascriptEl RonnocoView Answer on Stackoverflow
Solution 11 - Javascriptuser5676965418View Answer on Stackoverflow
Solution 12 - Javascriptha9u63arView Answer on Stackoverflow
Solution 13 - JavascriptyassineView Answer on Stackoverflow
Solution 14 - Javascriptuser2359695View Answer on Stackoverflow
Solution 15 - JavascriptBrendon-Van-HeyzenView Answer on Stackoverflow
Solution 16 - JavascriptlegendJSLCView Answer on Stackoverflow