Serialization with JSON
In the context of data storage and transmission, serialization is the name given to the process of converting data into a format that can be stored or transmitted across a network and recovered later into the same format as the original.
In the case of JSON, a string is the chosen format of the serialized data. To serialize your JSON object (for instance, to send it across a network connection), you need to express it as a string.
In later browsers, those having JSON support, you can simply use the JSON.stringify() method.
JSON.stringify()
You can create a JSON-encoded string of an object using the JSON.stringify()
method.
Let’s create a simple object and add some properties:
var Dan = new Object(); Dan.height = 1.85; Dan.age = 41; Dan.eyeColor = "blue";
Now you can serialize the object using JSON.stringify:
alert( JSON.stringify(Dan) );
The serialized object is shown as
Try it Yourself: Parsing a JSON String
Create an HTML file using your editor, and enter the code
<!DOCTYPE html> <html> <head> <title>Parsing JSON</title> <script> function jsonParse() { var inString = prompt("Enter JSON object"); var out = ""; myObject = JSON.parse(inString); for (i in myObject) { out += "Property: " + i + " = " + myObject[i] + '\n'; } alert(out); } </script> </head> <body onload="jsonParse()"> </body> </html>
The function jsonParse() is called when the page finishes loading, by using the onload event handler of the window object attached to the <body> element of the page.
The first line of code inside the function invites you to enter a string corresponding to a JSON object:
var inString = prompt("Enter JSON object");
Type it carefully, remembering to enclose any strings in quotation marks, as in
The script then declares an empty string variable called out, which later holds the output message:
var out = "";
The JSON.parse() method is then used to create an object based on the input string:
myObject = JSON.parse(inString);
You can now build your output message string by looping around the object methods:
for (i in myObject) { out += "Property: " + i + " = " + myObject[i] + '\n'; }
Finally, display the result:
alert(out);
The output message should look like the one
Reload the page and retry the script with a different number of
"parameter":"value" pairs.