Javascript 在javascript中附加到json文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12290572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
appending to json file in javascript
提问by Mike
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":"[email protected]","phone":"800-597-9405","image":"images/jerry.jpg" },' +
'{"firstName":"Ed","lastName":"Snide","time":"9:00 am","email":"[email protected]","phone":"800-597-9406","image":"images/ed.jpg" },' +
'{"firstName":"Pattabhi","lastName":"Nunn","time":"10:15 am","email":"[email protected]","phone":"800-597-9407","image":"images/pattabhi.jpg" }'+
']}';
I would like to append:
我想补充:
- firstName:Mike
- lastName:Rut
- time:10:00 am
- email:[email protected]
- phone:800-888-8888
- image:images/mike.jpg
- 名字:迈克
- 姓氏:车辙
- 时间:上午10:00
- 电子邮件:[email protected]
- 电话:800-888-8888
- 图像:图像/迈克.jpg
to employee.json.
到员工.json。
How would I accomplish this?
我将如何做到这一点?
回答by Van Coding
var data = JSON.parse(txt); //parse the JSON
data.employees.push({ //add the employee
firstName:"Mike",
lastName:"Rut",
time:"10:00 am",
email:"[email protected]",
phone:"800-888-8888",
image:"images/mike.jpg"
});
txt = JSON.stringify(data); //reserialize to JSON
回答by Ibu
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 ....
});