[javascript] Difference between JSON.stringify and JSON.parse

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

This question is related to javascript json

The answer is


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.


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

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>

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


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"]

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" }

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


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

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

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.


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


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>

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

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


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.


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.