我如何在 javascript 中动态构建 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4314008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do i build JSON dynamically in javascript?
提问by Saftsoppa
var myJSON = {
"list1" : [ "1", "2" ],
"list2" : [ "a", "b" ],
"list3" : [ { "key1" : "value1" }, { "key2" : "value2" } ],
"not_a_list" : "11"
};
How do I dynamically build this JSON structure in javascript? Google tells me to use use some push command, but I've only found specific cases. So what do I write to enter data to "listX" and "not_a_list". Appending as well as creating a new list. The whole procedure begninning with:
如何在 javascript 中动态构建这个 JSON 结构?谷歌告诉我使用一些推送命令,但我只找到了特定的情况。那么我写什么来输入数据到“listX”和“not_a_list”。追加以及创建新列表。整个过程开始于:
var myJSON = {};
回答by Neall
First, I think you're calling it the wrong thing. "JSON" stands for "JavaScript Object Notation" - it's just a specification for representing some data in a string that explicitly mimics JavaScript object (and array, string, number and boolean) literals. You're trying to build up a JavaScript object dynamically - so the word you're looking for is "object".
首先,我认为你称之为错误的事情。“JSON”代表“JavaScript Object Notation”——它只是一种在字符串中表示一些数据的规范,它明确地模仿了 JavaScript 对象(以及数组、字符串、数字和布尔值)文字。您正在尝试动态构建 JavaScript 对象 - 因此您要查找的词是“对象”。
With that pedantry out of the way, I think that you're asking how to set object and array properties.
有了这种迂腐,我认为您是在问如何设置对象和数组属性。
// 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';
That code will build up the object that you specified in your question (except that I call it myObject instead of myJSON). For more information on accessing properties, I recommend the Mozilla JavaScript Guideand the book JavaScript: The Good Parts.
该代码将构建您在问题中指定的对象(除了我将其称为 myObject 而不是 myJSON)。有关访问属性的更多信息,我推荐Mozilla JavaScript 指南和JavaScript: The Good Parts一书。
回答by AndreKR
As myJSON
is an object you can just set its properties, for example:
作为myJSON
一个对象,您可以只设置其属性,例如:
myJSON.list1 = ["1","2"];
If you dont know the name of the properties, you have to use the array access syntax:
如果您不知道属性的名称,则必须使用数组访问语法:
myJSON['list'+listnum] = ["1","2"];
If you want to add an element to one of the properties, you can do;
如果要将元素添加到属性之一,则可以这样做;
myJSON.list1.push("3");