10

我有一个 json 文件,employees.json,我想将数据附加到这个对象。该文件如下所示:

var txt = '{"employees":[' +
'{"firstName":"Jerry","lastName":"Negrell","time":"9:15 am","email":"jerry@bah.com","phone":"800-597-9405","image":"images/jerry.jpg" },' +
'{"firstName":"Ed","lastName":"Snide","time":"9:00 am","email":"edward@bah.com","phone":"800-597-9406","image":"images/ed.jpg" },' +
'{"firstName":"Pattabhi","lastName":"Nunn","time":"10:15 am","email":"pattabhi@bah.com","phone":"800-597-9407","image":"images/pattabhi.jpg" }'+
']}';

我想附加:

  • 名字:迈克
  • 姓氏:车辙
  • 时间:上午10:00
  • 电子邮件:rut@bah.com
  • 电话:800-888-8888
  • 图片:图片/mike.jpg

到雇员.json。

我将如何做到这一点?

4

2 回答 2

13
var data = JSON.parse(txt);  //parse the JSON
data.employees.push({        //add the employee
    firstName:"Mike",
    lastName:"Rut",
    time:"10:00 am",
    email:"rut@bah.com",
    phone:"800-888-8888",
    image:"images/mike.jpg"
});
txt = JSON.stringify(data);  //reserialize to JSON
于 2012-09-05T22:20:54.490 回答
5

JSON 代表 Javascript 对象表示法,因此这可能只是一个 javascript 对象

var obj = {employees:[
    {
      firstname:"jerry"
      ... and so on ...
     }
]};

当您想添加一个对象时,您可以简单地执行以下操作:

object.employees.push({
   firstname: "Mike",
   lastName: "rut"
    ... and so on ....
});
于 2012-09-05T22:21:16.963 回答