在Javascript中形成Json字符串所需的帮助

时间:2010-12-24 13:25:35

标签: string json

你好我必须在这样的javascript中创建一个json sting

{widget_list:[{widget_id:1,new_position:2},{widget_id:2,new_position:3},  .  .  .]}

使用json.org库。我使用这个库的功能是

  

var json_text =   JSON.stringify(已上传,“”,“”);

这创建了一个完美的json字符串,我可以在没有数组时生成

function uploaded()
{

}
var uploaded = new Uploaded();
uploaded.widget_id = 1;
uploaded.new_position = 2;
var json_text = JSON.stringify(uploaded, "", "");

当你警告json_text你将得到{“widget_id”:1,“new_position”:2}要求只是从json.org下载一个json2.js文件,用于javascript并包含它。

所以请帮助一些我无法创建的逻辑问题.... 提前谢谢....

2 个答案:

答案 0 :(得分:0)

uploaded = {};
var a = [];

uploaded.widget_id = 1;
uploaded.new_position = 2;
a[0] = uploaded;

uploaded.widget_id = 2;
uploaded.new_position = 3;
a[1] = uploaded;
uploaded_new = {}
uploaded_new.widget_list = a
alert( JSON.stringify(uploaded_new, "", ""));

提醒

{"widget_list":[{"widget_id":2,"new_position":3},{"widget_id":2,"new_position":3}]}

答案 1 :(得分:0)

我遇到了这个寻找类似解决方案,因为它有所帮助。但是你需要重新初始化“上传的”对象,否则它会覆盖现有的值。

所以,通过稍加修改,它将是

uploaded = {};
var a = [];

uploaded.widget_id = 1;
uploaded.new_position = 2;
a[0] = uploaded;

**uploaded = {};**

uploaded.widget_id = 2;
uploaded.new_position = 3;
a[1] = uploaded;
uploaded_new = {}
uploaded_new.widget_list = a
alert( JSON.stringify(uploaded_new, "", ""));