JSON objects .. inside JSON objects
Omit the curly braces:
var Person = { name: 'John', age: 21, alive: true, siblings: [ Andrew, { name: 'Christine', age: 19, alive: true } ] }
Andrew
is a reference to a JavaScript object. The curly brace notation - { foo: 1 }
- is an object literal. To use a variable instead of a literal, you omit the entire literal syntax, including the curly braces.
Note that neither of these is JSON or a "JSON object". JSON is a string that happens to match JavaScript Object literal syntax. Once a JSON string has been parsed, it is a JavaScript object, not a JSON object.
For example, this is valid JavaScript, but not valid JSON:
var Person = { name: "John", birthDate: new Date(1980, 0, 1), speak: function(){ return "hello"; }, siblings: [ Andrew, Christine ];}
JSON cannot instantiate objects such as new Date()
, JSON cannot have a function as a member, and JSON cannot reference external objects such as Andrew
or Christine
.
You're close. Andrew
is already an object, so you don't need to wrap it in the object literal syntax (and you'd need a property name to accompany it as the value if you did that). How about this:
var Andrew = { name: 'Andrew', age: 21, alive: true}var Person = { name: 'John', age: 21, alive: true, siblings: [ Andrew, { name: 'Christine', age: 19, alive: true } ] }
var Andrew = { name: 'Andrew', age: 21, alive: true}var Person = { name: 'John', age: 21, alive: true, siblings: [ Andrew, { name: 'Christine', age: 19, alive: true } ] }
Drop the brackets since it is already an object.
Person.siblings[0].name // Andrew