JSON对象..在JSON对象中 [英] JSON objects .. inside JSON objects

查看:91
本文介绍了JSON对象..在JSON对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我是JSON的新手,并且一直在尝试一些可能性。有一件事我想知道:有没有办法将'JSON对象放在'JSON对象'中?我想假设这可以完成,并且希望它可以,因为它可能非常很有用,但是语法的所有尝试都让我失望了。以下是该标准的示例:

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?

编辑:我的意思是:JSON是否能够对包含对象的对象进行编码他们?

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

推荐答案

省略花括号:

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

Andrew 是JavaScript的引用宾语。大括号表示法 - {foo:1} - 是一个对象 literal 。要使用变量而不是文字,请省略整个文字语法,包括花括号。

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.

请注意,这些都不是JSON或JSON对象。 JSON是一个恰好与JavaScript Object文字语法匹配的字符串。一旦解析了JSON字符串,它就是一个JavaScript对象,而不是JSON对象。

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.

例如,这是有效的JavaScript,但不是有效的JSON:

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无法实例化等新对象() ,JSON不能将函数作为成员,JSON不能引用外部对象,如 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.

这篇关于JSON对象..在JSON对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆