4

jsでJSONオブジェクトを作成しようとしています。スタックオーバーフロー自体には、このトピックに関するいくつかの投稿がすでにあります。JavaScriptでJSONを動的に構築するにはどうすればよいですか?。投稿で言及されているのとまったく同じように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が未定義としてエラーが発生します。

どこが悪いのかわからない。いくつかの宣言の問題があるに違いないと仮定します。どんな光でも大いに役立ちます。

4

3 に答える 3

9

これを試して:

 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オブジェクトを見てください。そこにはたくさんのものがあります。例: http: //mckoss.com/jscript/object.htm

編集privilege.attribute[0] = {};コメントのヒントの後に初期化されます。

于 2013-02-07T13:49:26.950 に答える
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"
        }
    }]
}
于 2013-02-07T13:51:27.027 に答える
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";
于 2013-02-07T13:49:26.510 に答える