reasons for variations in results
The reason behind the differing outputs lies in the distinct inputs provided.
SCENARIO ONE
obj = {a:"asdf"};
var newObj = JSON.parse(JSON.stringify(obj));
In this scenario, the parameter passed to JSON.parse
is the result of JSON.stringify(obj)
, which produces a string identical to {"a":"asdf"}
.
SCENARIO TWO
var newObj = JSON.parse("{"a":"asdf"}");
In this case, the parameter supplied to JSON.parse
contains an error as it starts with {
and then becomes invalid code.
Confusion may arise because when displayed in the console, strings are enclosed in double quotes ("
) to indicate their type, but these are not part of the actual string content.
To avoid this misunderstanding, try using alert or document.write instead of console.log if seeing an extra set of double quotes around the string obtained from JSON.stringify(obj). These methods will display the true value without additional formatting.
<html><head></head><body>
<script>
function JSONparse(string) {
document.write(string);
alert(string);
console.log(string);
return JSON.parse(string);
}
var obj = {a:"asdf"};
result = JSONparse(JSON.stringify(obj));
</script>
</body></html>