Difference Between Console.log(obj) And Console.log(json.stringify(obj))
Solution 1:
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.
JSON.stringify(obj, null, 2)
you can make it print more nicely. The last number determines the amount of spaces in indentation:
console.log(obj)
Using the Console API you can print any object to the console. This will work on any browser.
Solution 2:
Look at this code that the result in console.log is mutating.
const obj = {
value: 5
};
console.log(obj);
setTimeout(() => {
obj.value = 10;
}, 100);
You can get original value if use console.log(JSON.stringify(obj))
const obj = {
value: 5
};
console.log(JSON.stringify(obj));
setTimeout(() => {
obj.value = 10;
}, 100);
Solution 3:
When you are getting data from json created you can make your question more clear like this way
1) console.log(obj) -> means you will get json Javascript object like in javascript serialize array
2) console.log(JSON.stringify(obj)) -> means you will get that json Javascript object to string and then you will use for getting data in this way for(var i in (JSON.stringify(obj)) { }
you can easily get data inside that json
or if you want to convert again in javascript object you can use JSON.parse(JSON.stringify(obj))
then the data becomes a JavaScript object.
example :
var obj = { name: "John", age: 30, city: "New York" };
1) Use the JavaScriptfunctionJSON.stringify() to convert it into a string.
var myJSON = JSON.stringify(obj);
2) Use the JavaScriptfunctionJSON.parse() to convert text-string into a JavaScriptobject:
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
1) console.log(obj);
output : {name: "John", age: 30, city: "New York"}
2) console.log(myJSON );
output : {"name":"John","age":30,"city":"New York"}
2) console.log( JSON.parse(myJSON ));
output : {name: "John", age: 30, city: "New York"}
I Hope I Make it clear your question!
Post a Comment for "Difference Between Console.log(obj) And Console.log(json.stringify(obj))"