[javascript] Parse JSON in JavaScript?

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?

This question is related to javascript json parsing

The answer is


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

If you use Dojo Toolkit:

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

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

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.


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;

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.


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

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;

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

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

An easy way to do it:

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

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

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.


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

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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to parsing

Got a NumberFormatException while trying to parse a text file for objects Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Python/Json:Expecting property name enclosed in double quotes Correctly Parsing JSON in Swift 3 How to get response as String using retrofit without using GSON or any other library in android UIButton action in table view cell "Expected BEGIN_OBJECT but was STRING at line 1 column 1" How to convert an XML file to nice pandas dataframe? How to extract multiple JSON objects from one file? How to sum digits of an integer in java?