Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON objects .. inside JSON objects

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?

like image 526
grep Avatar asked Aug 11 '11 19:08

grep


1 Answers

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.

like image 181
gilly3 Avatar answered Oct 08 '22 09:10

gilly3