Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

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

2 Answers

akshay1995
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"
RoliMishra
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

Login / Signup to Answer the Question.