JSON is text, remember? It is created in many cases by serializing an object. Some intrepid programmers even write it directly as text. The standard document has no requirement for methods to change the text (back) into an object. It does however, make good sense for any using programming language to create at least two methods for handling JSON, a parser[27], and a serializer[28].
In order to use JSON in JavaScript we must change into
an object.
This is called
deserializing, and may, strictly speaking,
be done in either of two ways: with JSON.parse
,
or with eval
.
A word of advice, never
use the latter, always use
JSON.parse
.
In Crockford's, [Cro08],
words, “the eval
function has horrendous
security problems”.
We showed you an example of JSON.parse
a short
while ago, here is another:
JSON.parse
let myJsonString = '{ "name": "Aarhus", "population": 340421, "country": "DNK" }';
let myJsonObject = JSON.parse(myJsonString);
document.write(`<p>${myJsonObject.name} has ${myJsonObject.population} inhabitants</p>`);
The opposite of deserialization is (of course)
serialization, makes an object into a text
whenever that is necessary. The JavaScript function to do that
is very appropriately called JSON.stringify()
.
JSON.stringify
<!doctype html>
<html>
<head>
<meta charset='utf-8'/>
<title>Niels JSON.stringify Demo</title>
<script>
let obj = {
name: "LS",
species: "Cat",
age: 15,
declawed: false,
toString() {
let s = "";
s += `My name is ${obj.name}, I am a ${obj.species}, and I am ${obj.age} years old`;
return s;
}
}
</script>
</head>
<body>
<h1>Niels' JSON Demo - Stringify</h1>
<script>
document.write(`<p>${obj.toString()}</p>`);
let serializedObj = JSON.stringify(obj);
document.write(`<pre>${serializedObj}</pre>`);
serializedObj = JSON.stringify(obj, null, "\t");
document.write(`<pre>${serializedObj}</pre>`);
</script>
</body>
</html>
Please notice that, as mentioned earlier, that methods are not serialized to JSON text output. They are ignored.