Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
188
rated 0 times [  190] [ 2]  / answers: 1 / hits: 82989  / 13 Years ago, thu, august 11, 2011, 12:00:00

so I am new to JSON, and have been experimenting around with some possibilities. One thing I was wondering: Is there a way to place 'JSON object's inside of 'JSON objects'? I want to assume this can be done, and would like it to be possible as it could be very useful, but all attempts at the syntax has failed me. Here is an example of the standard:



var Person = {
name: 'John',
age: 21,
alive: true,
siblings: [
{
name: 'Andrew',
age: 23,
alive: true
},
{
name: 'Christine',
age: 19,
alive: true
}
]
}


Now, is there a way to do something like the following?



var Andrew = {
name: 'Andrew',
age: 21,
alive: true
}

var Person = {
name: 'John',
age: 21,
alive: true,
siblings: [
{
Andrew
},
{
name: 'Christine',
age: 19,
alive: true
}
]
}


If so, what is the proper way to do this? Or can it simply, not be done?



edit: What I really mean is: Is JSON able to encode objects which have objects inside of them?


More From » json

 Answers
17

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.


[#90667] Wednesday, August 10, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mathewb

Total Points: 535
Total Questions: 95
Total Answers: 96

Location: British Indian Ocean Territory
Member since Fri, Oct 15, 2021
3 Years ago
;