Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?     } }); 
like image 435
HIRA THAKUR Avatar asked Jul 22 '13 10:07

HIRA THAKUR


People also ask

Is JSON parse opposite of JSON Stringify?

JSON. stringify() is the opposite of JSON. parse(), which converts JSON into Javascript objects.

What is the purpose of JSON Stringify () and parse () methods?

stringify() The JSON. stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

What is JSON parse?

JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. parse() , as the Javascript standard specifies.

Is JSON parse and Stringify slow?

parse: 702 ms. Clearly JSON. parse is the slowest of them, and by some margin.


2 Answers

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"  
like image 126
Quentin Avatar answered Sep 19 '22 12:09

Quentin


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

like image 39
Bjorn 'Bjeaurn' S Avatar answered Sep 21 '22 12:09

Bjorn 'Bjeaurn' S