我对JSON世界有点新鲜。我必须使用JavaScript来创建以下类型的JSON结构。不知道如何实现这一目标。尝试使用以下代码,但无法将第二个元素(“12101”)以及人员添加到JSON Structure是我正在努力的地方。
var chat = {};
chat = {"101":{}};
chat["101"].people= {};
chat["101"].people = {"L0b12leL-Ar9GYKoAAAC":{}};
chat["101"].people.L0b12leL-Ar9GYKoAAAC = {"name":"vikram@qech.com"};
chat["101"].room= {};
实现JSON结构
{
"101": {
"people": {
"L0b12leL-Ar9GYKoAAAC": {
"name": "vikram@qtech.com",
"inroom": "f787f316-6424-491b-b779-cfc396f0f8a1",
"owns": "f787f316-6424-491b-b779-cfc396f0f8a1",
"countrycode": "in",
"device": "desktop",
"roomname": "R1"
},
"qKCglYWI1hRhZUZCAAAD": {
"name": "Ishim",
"inroom": "2e52905d-951c-4990-b9b7-2f3fc0602922",
"owns": "2e52905d-951c-4990-b9b7-2f3fc0602922",
"roomname": "Ra"
}
},
"room": {
"f787f316-6424-491b-b779-cfc396f0f8a1": {
"name": "R1",
"id": "f787f316-6424-491b-b779-cfc396f0f8a1",
"owner": "L0b12leL-Ar9GYKoAAAC",
"people": [
"L0b12leL-Ar9GYKoAAAC"
],
"status": "available"
},
"2e52905d-951c-4990-b9b7-2f3fc0602922": {
"name": "Ra",
"id": "2e52905d-951c-4990-b9b7-2f3fc0602922",
"owner": "qKCglYWI1hRhZUZCAAAD",
"people": [
"qKCglYWI1hRhZUZCAAAD"
],
"status": "available"
}
}
},
"12101": {
"people": {
"K-Ar9GYKoAAAC": {
"name": "Rahul.com",
"inroom": "f787f316-6424-491b-b779-cfc396f0f8a1",
"owns": "f787f316-6424-491b-b779-cfc396f0f8a1",
"countrycode": "in",
"device": "desktop",
"roomname": "R1"
},
"I1hRhZUZCAAAD": {
"name": "Vipul",
"inroom": "2e52905d-951c-4990-b9b7-2f3fc0602922",
"owns": "2e52905d-951c-4990-b9b7-2f3fc0602922",
"roomname": "Ra"
}
},
"room": {
"b779-cfc396f0f8a1": {
"name": "Rahul-R1",
"id": "f787f316-6424-491b-b779-cfc396f0f8a1",
"owner": "L0b12leL-Ar9GYKoAAAC",
"people": [
"L0b12leL-Ar9GYKoAAAC"
],
"status": "available"
},
"b9b7-2f3fc0602922": {
"name": "Vipul-Room1",
"id": "2e52905d-951c-4990-b9b7-2f3fc0602922",
"owner": "qKCglYWI1hRhZUZCAAAD",
"people": [
"qKCglYWI1hRhZUZCAAAD"
],
"status": "available"
}
}
}
}
答案 0 :(得分:3)
这是无效的,因为属性名称包含破折号。
chat["101"].people.L0b12leL-Ar9GYKoAAAC = {"name":"vikram@qech.com"};
要正确访问它,请将其放在引号
中chat["101"].people["L0b12leL-Ar9GYKoAAAC"] = {"name":"vikram@qech.com"};
答案 1 :(得分:2)
像这样使用bracket notation as a property accessor:
chat["12101"].people = {};
chat["101"].people["L0b12leL-Ar9GYKoAAAC"] = {"name":"vikram@qech.com"};
有了它,它只是一项例行工作。它可能不会立即起作用,因为点符号属性访问需要valid identifier name。使用括号表示法,您可以使用任何字符串,如"L0b12leL-Ar9GYKoAAAC"
。
另请注意,在JSON中,任何内容都可以作为属性名称使用,只要它放在引号中即可。 {"L0b12leL-Ar9GYKoAC":true}
as valid为{"":true}
。