HTML and CSS Reference
In-Depth Information
JavaScript Object Notation , or JSON , is a lightweight data interchange format used to transmit data over a network.
It uses a human-readable, standardized syntax to define data objects that can be parsed by many computer programs.
Here is an example of how to define a simple JavaScript object in JSON.
“name": “Joe Balochio",
“age": “28",
“gender": “male"
You define a new object in JSON using curly braces {} and then use key/value pairs to define the object's proper-
ties. A colon is used to separate a key from its value, and commas separate each of the properties in the object.
JSON objects can easily be serialized and parsed by libraries present in many programming languages. Serialization
is the process of taking an object in your code and converting it to a JSON object, like the one in the example above.
Parsing is the opposite; it takes a JSON object and converts it to an object that can be used in your JavaScript code.
The JSON Object
Many programming languages have built-in libraries that provide support for JSON. In JavaScript, you can use the
JSON object to make use of the JSON library present in most browsers (excluding IE7 and below). This object has
several available functions that you can use to help handle JSON data.
The first function that we are going to look at is stringify() . This function converts an object (or objects) into a
JSON object(s) and then returns that JSON as a string. Let's test this out.
Open your console and create a new JavaScript object by entering the following statements:
var person = {}; = “Joe Balochio";
person.age = 28;
person.gender = “male";
Now that you have created a JavaScript object, use the stringify() function to convert it to JSON.
var jsonPerson = JSON.stringify(person);
This converts the person object to JSON and saves the result to the jsonPerson variable. You can output the
JSON by inspecting the jsonPerson variable in the console (just type jsonPerson and press Enter). Figure
12-6 shows the expected output for this example.
Search WWH ::

Custom Search