在Javascript中构造JSON

时间:2013-02-07 13:44:58

标签: javascript json

我正在尝试在js中构造JSON对象。堆栈溢出本身已经有几个关于这个主题的帖子。提到How do i build JSON dynamically in javascript?。必须构建完全像帖子中提到的JSON。

{
    "privilege": {
        "accesstype": "VIEW",
        "attribute": [
            {
                "code": "contenttype",
                "displayname": "Content type",
                "value": {
                    "valcode": "book_article",
                    "valdisplayName": "Book Article"
                }
            },
            {
                "code": "mime",
                "displayname": "Mime type",
                "value": {
                    "valcode": "xml",
                    "valdisplayName": "Xml"
                }
            }
        ]
    }
}

在帖子中找到答案并尝试了这个,

var privilege = {};

privilege.attribute[0].code = "contenttype";
privilege.attribute[0].displayname = "Content type";
privilege.attribute[0].value.valcode = "book_article";
privilege.attribute[0].value.valdisplayName = "Book Article";

但是获取错误为privilege.attribute undefined。

我无法弄清楚我哪里出错了。假设必须有一些声明问题。对它有任何启发都会有很大的帮助。

3 个答案:

答案 0 :(得分:6)

试试这个:

 var privilege = {};
 privilege.attribute = [];
 privilege.attribute[0] = {};
 privilege.attribute[0].code="contenttype";
 privilege.attribute[0].displayname="Content type";
 privilege.attribute[0].value = {};
 privilege.attribute[0].value.valcode="book_article";
 privilege.attribute[0].value.valdisplayName="Book Article";

看看Javascript对象。那里有很多东西。 E.g http://mckoss.com/jscript/object.htm

修改:在提示评论后初始化privilege.attribute[0] = {};

答案 1 :(得分:1)

为什么不做呢

var privilege = {
    "accesstype": "VIEW",
    "attribute": [{
        "code": "contenttype",
        "displayname": "Content type",
        "value": {
            "valcode": "book_article",
            "valdisplayName": "Book Article"
        }
    }, {
        "code": "mime",
        "displayname": "Mime type",
        "value": {
            "valcode": "xml",
            "valdisplayName": "Xml"
        }
    }]
}

...实际上,你不需要键成为字符串,你可以写...

var privilege = {
    accesstype: "VIEW",
    attribute: [{
        code: "contenttype",
        displayname: "Content type",
        value: {
            valcode: "book_article",
            valdisplayName: "Book Article"
        }
    }, {
        code: "mime",
        displayname: "Mime type",
        value: {
            valcode: "xml",
            valdisplayName: "Xml"
        }
    }]
}

答案 2 :(得分:0)

试试这个

privilege.attribute = [];
privilege.attribute.push({});

privilege.attribute[0].code="contenttype";
privilege.attribute[0].displayname="Content type";
privilege.attribute[0].value.valcode="book_article";
privilege.attribute[0].value.valdisplayName="Book Article";