Difference Between JSON.Stringify and JSON.Parse

Difference between JSON.stringify and JSON.parse

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"

Do JSON.stringify() and JSON.parse() change data type?

JSON has no support for types other than object, array, null, string, number and boolean.

If you kind of know what you can expect in your JSON, you can use a reviver function during parsing. For your example, this suffices:

JSON.parse(string, (k, v) => v.hasOwnProperty('site')
? new Account(v.site, v.login, v.pass)
: v);

What is JSON.parse() and JSON.stringify() Doing in the Code Below. I am Building a Book Library

localStorage can keep data in string format so before you can use it as object data in Javascript you need to turn it in to an object using JSON.parse() method.

when saving it back to the localStorage, you need to turn it back to a string value using JSON.stringify()

JSON example confusing me - about JSON.parse, JSON.stringify, localStorage.setItem and localStorage.getItem

I'll run through each line step by step.

Saving

  1. myObj = {name: "John", age: 31, city: "New York"};

    • This line creates the object.
  2. myJSON = JSON.stringify(myObj);
    • This line turns the javascript object into a JSON string usable by any application that accepts JSON.
  3. localStorage.setItem("testJSON", myJSON);
    • Modern browsers have a localStorage API that allows you to store data in the browser. This line is storing that JSON string inside of localStorage for later use.

Retrieving


  1. text = localStorage.getItem("testJSON");
    • This line is retrieving the stored JSON string.
  2. obj = JSON.parse(text);
    • This parses the retrieved JSON string back into a Javascript object.
  3. document.getElementById("demo").innerHTML = obj.name;
    • This will access the name property of the object that you parsed and print it to the demo element on the page.

What is the use of stringify and then parse a JSON object

I think you may have a fundamental misunderstanding. JSON is a textual notation for data exchange. If you're dealing with JavaScript source code, and not dealing with a string, you're not dealing with JSON.

You don't "take a JSON object and stringify it." If it's an object, it's not JSON; if it's JSON notation for an object, it's a string and you wouldn't stringify it.

Here's an object:

var foo = {answer: 42};

Here's using stringify on it:

var str = JSON.stringify(foo);

Now str is a string containing JSON, with this content:


{"answer":42}

...exactly as though you had written this:

var str = '{"answer":42}';

You can parse that back into an object (note: not a "JSON object," just an object):

var foo2 = JSON.parse(str);

Now, foo refers to the original object, and foo2 refers to a different object with copies of the properties:

console.log(foo == foo2);               // false, they're different object
console.log(foo.answer == foo2.answer); // true, they each have an answer property
// and their values match
console.log(foo.answer); // 42
console.log(foo2.answer); // 42
foo2.answer = 67;
console.log(foo.answer); // 42 | the objects and their properties
console.log(foo2.answer); // 67 | are not connected in any way

Is there any specific reason for stringify a JSON object and parse it again.

Sometimes people use that as a poor man's cloning method, as the object you get back is not the same object you stringified; it's a new object with the same properties (provided that all of the properties of the original could be serialized to JSON; properties referring to functions or with the value undefined can't be, and many other values [such as dates] don't convert back without a "reviver" function for JSON.parse, so they end up being strings or numbers).

That fits with the code in the latest version of your question:

Code 1: stringify and then parse

var textstring = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
var obj=JSON.parse(textstring);
var obj2=JSON.parse(JSON.stringify(obj));

Code 2:Direct Use

var textstring = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
var obj=JSON.parse(textstring);
var obj2=obj;

(Note I changed text and text2 to obj and obj2; they aren't text.)

At the end of Code 1, obj and obj2 refer to different objects. If you change one of the properties on the object obj refers to, obj2 is completely unchanged:

// Replace the employees array with a blank one
obj.employees = [];

// No effect at all on obj2:
console.log(obj2.employees[0].firstName); // "John"

In contrast, of course, with Code 2 obj and obj2 are both references to the same object.

Reverse of JSON.stringify?

You need to JSON.parse() your valid JSON string.

var str = '{"hello":"world"}';
try {
var obj = JSON.parse(str); // this is how you parse a string into JSON
document.body.innerHTML += obj.hello;
} catch (ex) {
console.error(ex);
}

JSON Parse and JSON Stringify are not printing well

Very close! Two things:

First and major problem was, you were calling JSON.stringify(arrayInput); and not JSON.parse(arrayInput);, the parse function turns JSON string into a object.

Secondly, the buttonCreate.innerHTML = array[i] needed to be buttonCreate.innerHTML = array[i].name + "; " + array[i].interests;, this new code is actually pulling the properties out of your array element whereas your were just putting the whole object into the innerHTML; [Object object] gets printed out on your buttons.

Here is what you're looking for:

function load() {
var arrayInput = '[{"name" : "Jeff", "interests" : "3"}, {"name" : "Harry", "interests" : "2"}, {"name" : "Bob", "interests" : "coding"}, {"name" : "Jay", "interests" : "coding"}]';
var array = JSON.parse(arrayInput);
var resultBoxs = document.getElementById("resultBoxs");
for (var i = 0; i < array.length; i++) {
var buttonCreate = document.createElement("button");
buttonCreate.type = "checkbox";
buttonCreate.innerHTML = array[i].name + ";" + array[i].interests;
resultBoxs.appendChild(buttonCreate);
}
}
<body onload="load()">
<div id="resultBoxs"></div>
</body>

What is the difference between Object.assign and JSON.parse(JSON.stringify(obj)) for deep cloning of an object?

The difference is that

Object.assign({}, obj)

creates a shallow copy, not deep, while

JSON.parse(JSON.stringify(obj))

serializes the object as a JSON string and then deserializes it, effectively creating a deep copy. It should be noted that this method can only "deep copy" plain old data, not complex objects and their prototype.

A shallow copy is just fine, if all of your properties point to primitive values, or if you have no intention to mutate objects referenced by the copy. If you do, the changes will be visible in both the original and the shallow copy, because they both reference the same object:

> let a = { k: { h: 1 } };
> let b = Object.assign({}, a);
> b.k.h = 2;
> a
{ k: { h: 2 } }
> b
{ k: { h: 2 } }

You of course can mutate the copy itself without it having any effect on the original:

> b.j = 4
> b.k = { new: 'object' }
> a
{ k: { h: 2 } }
> b
{ k: { new: 'object' }, j: 4 }

The serialize-deserialize trick on the other hand creates a deep copy where everything is created from scratch:

> let c = JSON.parse(JSON.stringify(b));
> c
{ k: { h: 2 } }
> c.k.h = 3
> c
{ k: { h: 3 } }
> a
{ k: { h: 2 } }
> b
{ k: { h: 2 } }

Another way to inspect the identities is using strict equality:

> let a = { k: { h: 1 } };
> let b = Object.assign({}, a);
> a.k === b.k // both point to the same object
true
> let c = JSON.parse(JSON.stringify(b));
> c.k === b.k // different objects
false


Related Topics



Leave a reply



Submit