appending to json file in javascript

后端 未结 2 1253
-上瘾入骨i
-上瘾入骨i 2020-12-19 02:29

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

var txt = \'{\"employees\":[\' +
\'{\"firstNam         


        
相关标签:
2条回答
  • 2020-12-19 03:14
    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
    
    0 讨论(0)
  • 2020-12-19 03:23

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

    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 ....
    });
    
    0 讨论(0)
提交回复
热议问题