Difference between JSON.stringify and JSON.parse

JavascriptJson

Javascript Problem Overview


I have been confused over when to use these two parsing methods.

After I echo my json_encoded data and retrieve it back via ajax, I often run into confusion about when I should use JSON.stringify and JSON.parse.

I get [object,object] in my console.log when parsed and a JavaScript object when stringified.

$.ajax({
url: "demo_test.txt",
success: function(data) {
         console.log(JSON.stringify(data))
                     /* OR */
         console.log(JSON.parse(data))
        //this is what I am unsure about?
    }
});

Javascript Solutions


Solution 1 - Javascript

JSON.stringify turns a JavaScript object into JSON text and stores that JSON text in a string, eg:

var my_object = { key_1: "some text", key_2: true, key_3: 5 };

var object_as_string = JSON.stringify(my_object);  
// "{"key_1":"some text","key_2":true,"key_3":5}"  

typeof(object_as_string);  
// "string"  

JSON.parse turns a string of JSON text into a JavaScript object, eg:

var object_as_string_as_object = JSON.parse(object_as_string);  
// {key_1: "some text", key_2: true, key_3: 5} 

typeof(object_as_string_as_object);  
// "object" 

Solution 2 - Javascript

JSON.parse() is for "parsing" something that was received as JSON.
JSON.stringify() is to create a JSON string out of an object/array.

Solution 3 - Javascript

They are the inverse of each other. JSON.stringify() serializes a JS object into a JSON string, whereas JSON.parse() will deserialize a JSON string into a JS object.

Solution 4 - Javascript

They are the opposites of each other.

JSON.stringify()

JSON.stringify() serializes a JS object or value into a JSON string.

JSON.stringify({});                  // '{}'
JSON.stringify(true);                // 'true'
JSON.stringify('foo');               // '"foo"'
JSON.stringify([1, 'false', false]); // '[1,"false",false]'
JSON.stringify({ x: 5 });            // '{"x":5}'

JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)) 
// '"2006-01-02T15:04:05.000Z"'

JSON.stringify({ x: 5, y: 6 });
// '{"x":5,"y":6}' or '{"y":6,"x":5}'
JSON.stringify([new Number(1), new String('false'), new Boolean(false)]);
// '[1,"false",false]'

JSON.parse()

The JSON.parse() method parses a string as JSON, optionally transforming the value produced.

JSON.parse('{}');              // {}
JSON.parse('true');            // true
JSON.parse('"foo"');           // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null');            // null

Solution 5 - Javascript

Firstly, JSON.stringify() function converts a JavaScript value to a JavaScript Object Notation (JSON) string. JSON.parse() function converts a JavaScript Object Notation (JSON) string into an object. For more information about these two functions, please refer to the following links.

https://msdn.microsoft.com/library/cc836459(v=vs.94).aspx https://msdn.microsoft.com/library/cc836466(v=vs.94).aspx

Secondly, the following sample will be helpful for you to understand these two functions.

<form id="form1" runat="server">
    <div>
        <div id="result"></div>
    </div>
</form>

<script>
    $(function () {
        //define a json object
        var employee = { "name": "John Johnson", "street": "Oslo West 16", "phone": "555 1234567" };

        //use JSON.stringify to convert it to json string
        var jsonstring = JSON.stringify(employee);
        $("#result").append('<p>json string: ' + jsonstring + '</p>');

        //convert json string to json object using JSON.parse function
        var jsonobject = JSON.parse(jsonstring);
        var info = '<ul><li>Name:' + jsonobject.name + '</li><li>Street:' + jsonobject.street + '</li><li>Phone:' + jsonobject.phone + '</li></ul>';

        $("#result").append('<p>json object:</p>');
        $("#result").append(info);
    });
</script>

Solution 6 - Javascript

var log = { "page": window.location.href, 
        "item": "item", 
        "action": "action" };

log = JSON.stringify(log);
console.log(log);
console.log(JSON.parse(log));

//The output will be:

//For 1st Console is a String Like:

'{ "page": window.location.href,"item": "item","action": "action" }'

//For 2nd Console is a Object Like:

Object {
page   : window.location.href,	
item   : "item",
action : "action" }

Solution 7 - Javascript

JSON.stringify() Converts an object into a string.

JSON.parse() Converts a JSON string into an object.

Solution 8 - Javascript

The real confusion here is not about parse vs stringify, it's about the data type of the data parameter of the success callback.

data can be either the raw response, i.e a string, or it can be an JavaScript object, as per the documentation:

> success > > Type: Function( Anything data, String textStatus, jqXHR jqXHR ) A > function to be called if the request succeeds. The function gets > passed three arguments: The data returned from the server, formatted > according to the dataType parameter or the dataFilter callback > function, if specified;<..>

And the dataType defaults to a setting of 'intelligent guess'

> dataType (default: Intelligent Guess (xml, json, script, or html)) > > Type: String The type of data that you're expecting back from the > server. If none is specified, jQuery will try to infer it based on the > MIME type of the response (an XML MIME type will yield XML, in 1.4 > JSON will yield a JavaScript object, in 1.4 script will execute the > script, and anything else will be returned as a string).

Solution 9 - Javascript

They are the complete opposite of each other.

JSON.parse() is used for parsing data that was received as JSON; it deserializes a JSON string into a JavaScript object.

JSON.stringify() on the other hand is used to create a JSON string out of an object or array; it serializes a JavaScript object into a JSON string.

Solution 10 - Javascript

JavaScript Object <-> JSON String


JSON.stringify() <-> JSON.parse()

JSON.stringify(obj) - Takes any serializable object and returns the JSON representation as a string.

JSON.stringify() -> Object To String.

JSON.parse(string) - Takes a well formed JSON string and returns the corresponding JavaScript object.

JSON.parse() -> String To Object.

Explanation: JSON.stringify(obj [, replacer [, space]]);

Replacer/Space - optional or takes integer value or you can call interger type return function.

function replacer(key, value) {
    if (typeof value === 'number' && !isFinite(value)) {
        return String(value);
    }
    return value;
}
  • Replacer Just Use for replace non finite no with null.
  • Space use for indenting Json String by space

Solution 11 - Javascript

They are opposing each other. JSON.Stringify() converts JSON to string and JSON.Parse() parses a string into JSON.

Solution 12 - Javascript

I don't know if it's been mentioned, but one of the uses of JSON.parse(JSON.stringify(myObject)) is to create a clone of the original object.

This is handy when you want to mess with some data without affecting the original object. Probably not the cleanest / fastest way but certainly the simplest for objects that aren't massively complex.

Solution 13 - Javascript

JSON.stringify(obj [, replacer [, space]]) - Takes any serializable object and returns the JSON representation as a string.

JSON.parse(string) - Takes a well formed JSON string and returns the corresponding JavaScript object.

Solution 14 - Javascript

JSON : It is mainly used to exchange data to/from the server. Before sending the JSON object to the server, it has to be a string.

JSON.stringify() //Converts the JSON object into the string representation.
var jsonData={"Name":"ABC","Dept":"Software"};// It is a JSON object
var jsonString=JSON.stringify(jsonData);// It is a string representation of the object
// jsonString === '{"Name":"ABC","Dept":"Software"}'; is true

It also converts the Javascript array into string

var arrayObject=["ABC","Software"];// It is array object
var arrString=JSON.stringify(array);// It is string representation of the array (object)
// arrString === '["ABC","Software"]'; is true 

When we received the JSON data from the server, the data would be the string format.Hence we convert the string into JSON object.

JSON.parse() //To convert the string into JSON object.
var data='{ "name":"ABC", "Dept":"Software"}'// it is a string (even though it looks like an object)
var JsonData= JSON.parse(data);// It is a JSON Object representation of the string.
// JsonData === { "name":"ABC", "Dept":"Software"}; is true

Solution 15 - Javascript

JSON.stringify() takes a JavaScript object and then transforms it into a JSON string. JSON.parse() takes a JSON string and then transforms it into a JavaScript object.

const myObject = { dog: "", cat: "", koala: "", count: 3 };

console.log(JSON.stringify(myObject)); // result: {"dog":"","cat":"","koala":"","count":3}

console.log(JSON.parse(JSON.stringify(myObject))); // result: Object {dog: "", cat: "", koala: "", count: 3}

Solution 16 - Javascript

JSON.parse() is used to convert String to Object.
JSON.stringify() is used to convert Object to String.

You can refer this too...

<script type="text/javascript">

function ajax_get_json(){
    
    var hr = new XMLHttpRequest();
   	hr.open("GET", "JSON/mylist.json", true);
    hr.setRequestHeader("Content-type", "application/json",true);
    hr.onreadystatechange = function() {
	    if(hr.readyState == 4 && hr.status == 200) {
		   /*  var return_data = hr.responseText; */
		   
		   var data=JSON.parse(hr.responseText);
		   var status=document.getElementById("status");
		   status.innerHTML = "";
		   /* status.innerHTML=data.u1.country;	 */
		   for(var obj in data)
			   {
			   status.innerHTML+=data[obj].uname+" is in "+data[obj].country+"<br/>";
			   }
		   
	    }
    }
    hr.send(null);
    status.innerHTML = "requesting...";
}
</script>

Solution 17 - Javascript

JSON.parse() takes a JSON string and transforms it into a JavaScript object.

JSON.stringify() takes a JavaScript object and transforms it into a JSON string.

const myObj = {
      name: 'bipon',
      age: 25,
      favoriteFood: 'fish curry'
};

 const myObjStr = JSON.stringify(myObj);

console.log(myObjStr);
// "{"name":"bipon","age":26,"favoriteFood":"fish curry"}"

console.log(JSON.parse(myObjStr));
 // Object {name:"bipon",age:26,favoriteFood:"fish curry"}
And although the methods are usually used on objects, they can also be used on arrays:
const myArr = ['simon', 'gomez', 'john'];

const myArrStr = JSON.stringify(myArr);

console.log(myArrStr);
// "["simon","gomez","john"]"

console.log(JSON.parse(myArrStr));
// ["simon","gomez","john"]

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
QuestionHIRA THAKURView Question on Stackoverflow
Solution 1 - JavascriptQuentinView Answer on Stackoverflow
Solution 2 - JavascriptBjorn 'Bjeaurn' SView Answer on Stackoverflow
Solution 3 - JavascriptbluehalluView Answer on Stackoverflow
Solution 4 - JavascriptBhushan GadekarView Answer on Stackoverflow
Solution 5 - JavascriptMouView Answer on Stackoverflow
Solution 6 - JavascriptANIK ISLAM SHOJIBView Answer on Stackoverflow
Solution 7 - JavascriptHamed KamravaView Answer on Stackoverflow
Solution 8 - JavascriptPatrickView Answer on Stackoverflow
Solution 9 - Javascriptuser6788628View Answer on Stackoverflow
Solution 10 - JavascriptZigri2612View Answer on Stackoverflow
Solution 11 - JavascriptDavid CarmonaView Answer on Stackoverflow
Solution 12 - JavascriptP. BrownView Answer on Stackoverflow
Solution 13 - JavascriptnosdalgView Answer on Stackoverflow
Solution 14 - JavascriptSheo Dayal SinghView Answer on Stackoverflow
Solution 15 - Javascriptfatima hassanView Answer on Stackoverflow
Solution 16 - Javascriptpriya logView Answer on Stackoverflow
Solution 17 - JavascriptBipon BiswasView Answer on Stackoverflow