var myJSON = {
"list1" : [ "1", "2" ],
"list2" : [ "a", "b" ],
"list3" : [ { "key1" : "value1" }, { "key2" : "value2" } ],
"not_a_list" : "11"
};
如何在 javascript 中动态构建此 JSON 结构?谷歌告诉我使用一些推送命令,但我只找到了特定的案例。那么我要写什么来将数据输入“listX”和“not_a_list”。追加以及创建新列表。整个过程开始于:
var myJSON = {};
最佳答案
首先,我认为您称它为错误的东西。 “JSON”代表“JavaScript Object Notation”——它只是一种在字符串中表示某些数据的规范,该字符串明确模仿 JavaScript 对象(以及数组、字符串、数字和 bool 值)文字。您正在尝试动态构建 JavaScript 对象 - 因此您要查找的词是“对象”。
我认为您是在问如何设置对象和数组属性。
// make an empty object
var myObject = {};
// set the "list1" property to an array of strings
myObject.list1 = ['1', '2'];
// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';
myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
myObject.list3.push({});
// or unshift them on to the beginning
myObject.list3.unshift({});
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';
myObject.not_a_list = '11';
该代码将构建您在问题中指定的对象(除了我将其称为 myObject 而不是 myJSON)。有关访问属性的更多信息,我推荐 Mozilla JavaScript Guide和书JavaScript: The Good Parts .
关于javascript - 如何在 javascript 中动态构建 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4314008/