如何在JSON对象中动态添加数据

时间:2012-02-03 07:18:45

标签: json

示例代码

var mydata = [ {id:"1",invdate:"2007-10-01",name:"test",note:"note",amount:"200.00",tax:"10.00",total:"210.00"}, {id:"2",invdate:"2007-10-02",name:"test2",note:"note2",amount:"300.00",tax:"20.00",total:"320.00"}];

我必须得到类似上面的输出,必须将动态列及其值添加到mydata。

我正在尝试做这样的事情,但它不适合我。

var mydata = [];
for (var r = 0; r < dataTable.getNumberOfRows(); r++) {
  var items = "";
  var y ="";
   for (var c = 0; c < dataTable.getNumberOfColumns(); c++) {
     items += '"'+dataTable.getColumnLabel(c)+'":'+dataTable.getValue(r, c)
      if(c!=dataTable.getNumberOfColumns()-1){
        items += ",";
      }
   }
   y = "{"+items+"}";
   mydata.push(y);
}

上面的代码对我不起作用。任何其他方式

2 个答案:

答案 0 :(得分:5)

易:

oldJsonObj.vector = [] //this creates a new element into the object

foreach(dataTable.getNumberOfRows()){
  var x = {}
  x.id = XXX;
  x.name = XXX;
  oldJsonObj.vector.push(x); //adds the element x to array
}

alert(oldJsonObj.vector[i].name); //easy accses

答案 1 :(得分:4)

希望这可以帮到你:

var json = []; 

// add an field 'a'
json['a'] = 1;
alert(json["a"]);  //1 

// add an field 'b'
json['b'] = []; // another json object
...

在你的情况下:

mydata=[];

// add json fields
mydata["id"] = 1;
mydata["invdate"] = "2007-10-01";
mydata["name"] = "test";
//...