在javascript中附加到json文件

时间:2020-12-18 01:53:47

I have a json file, employees.json, that I would like to append data to this object. The file looks like this:

我有一个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" }'+
']}';

I would like to append:

我想补充一下:

  • firstName:Mike
  • lastName:Rut
  • time:10:00 am
  • email:rut@bah.com
  • phone:800-888-8888
  • image:images/mike.jpg

to employee.json.

How would I accomplish this?

我怎么做到这一点?

2 个解决方案

#1


9  

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

#2


3  

JSON stands for Javascript object notation so this could simply be a javascript object

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

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

When you want to add an object you can simply do:

如果要添加对象,只需执行以下操作:

object.employees.push({
   firstname: "Mike",
   lastName: "rut"
    ... and so on ....
});

#1


9  

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

#2


3  

JSON stands for Javascript object notation so this could simply be a javascript object

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

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

When you want to add an object you can simply do:

如果要添加对象,只需执行以下操作:

object.employees.push({
   firstname: "Mike",
   lastName: "rut"
    ... and so on ....
});