Java Reference
In-Depth Information
"age": 28,
"address": {
"numberAndStreet": "246 Someplace",
"city": "Somewhere",
"state": "Elsewhere"
}
}
]
This JSON array contains multiple objects that represent people and their addresses. The first is our
familiar John Doe, and the second is his little sister, Jane, who lives down the street. JSON data
structures can be as simple or complex as you need them to be.
serializing into Json
It's extremely easy to serialize JavaScript objects into JSON. JavaScript has an aptly named
JSON
object that you use to parse JSON data and serialize JavaScript objects. All major browsers support
this
JSON
object. Older browsers, such as IE7 and below, can use Crockford's JSON implementation
To serialize a JavaScript object into JSON, you use the
JSON
object's
stringify()
method. It accepts
any value, object, or array and serializes it into JSON. For example:
var person = {
firstName: "John",
lastName: "Doe",
age: 30
};
var json = JSON.stringify(person);
This code serializes the
person
object with
JSON.stringify()
and stores it in the
json
variable.
The resulting JSON‐formatted data looks like this:
{"firstName":"John","lastName":"Doe","age":30}
All unnecessary whitespace is removed, giving you an optimized payload that you can then send to
the web server or store elsewhere.
parsing Json
Parsing JSON into JavaScript objects is equally simple. The
JSON
object has a
parse()
method that
parses the JSON and returns the resulting object. Using the
json
variable from the previous code:
var johnDoe = JSON.parse(json);
This code parses the JSON text contained in
json
and stores the resulting object in the
johnDoe
variable. And here's the wonderful thing—you can immediately use
johnDoe
and access its
properties, such as:
var fullName = johnDoe.firstName + " " + johnDoe.lastName;