gpt4 book ai didi

javascript - 在 Javascript 中构建 JSON

转载 作者:搜寻专家 更新时间:2023-11-01 05:13:11 25 4
gpt4 key购买 nike

我正在尝试在 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。

我无法弄清楚我哪里出错了。假设肯定有一些声明问题。任何关于它的光都会有很大的帮助。

最佳答案

试试这个:

 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] = {};

关于javascript - 在 Javascript 中构建 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14752606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com