Javascript – Difference between JSON.stringify and JSON.parse

javascriptjson

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

Best Answer

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"