如何在javascript中动态构建JSON? [英] How do i build JSON dynamically in javascript?
问题描述
var myJSON = {
"list1" : [ "1", "2" ],
"list2" : [ "a", "b" ],
"list3" : [ { "key1" : "value1" }, { "key2" : "value2" } ],
"not_a_list" : "11"
};
如何在javascript中动态构建此JSON结构?谷歌告诉我使用一些推送命令,但我只找到了具体案例。那么我要写什么来输入数据到listX和not_a_list。添加以及创建新列表。整个过程包括:
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:
var myJSON = {};
推荐答案
首先,我认为你称之为错误事情。 JSON代表JavaScript Object Notation - 它只是一个用于在字符串中表示某些数据的规范,该字符串明确地模仿JavaScript对象(以及数组,字符串,数字和布尔值)文字。你正试图动态建立一个JavaScript对象 - 所以你要找的那个词就是对象。
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".
我认为这个迂腐之道你问的是如何设置对象和数组属性。
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';
该代码将构建您在问题中指定的对象(除了我称之为myObject而不是of myJSON)。有关访问属性的更多信息,我建议 Mozilla JavaScript指南和本书 JavaScript:好零件。
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 Guide and the book JavaScript: The Good Parts.
这篇关于如何在javascript中动态构建JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!