JSON数组类对象,添加项

时间:2016-02-01 21:11:26

标签: javascript arrays json node.js

我有一个包含以下内容的JSON文件:

[{"id":1,"first_name":"Judith","email":"jshaw0@wikipedia.org"},
{"id":2,"first_name":"Sarah","email":"sross1@infoseek.co.jp"},
{"id":3,"first_name":"Dorothy","email":"dgreene2@posterous.com"},
{"id":4,"first_name":"Christine","email":"cnichols3@techcrunch.com"},
{"id":5,"first_name":"Theresa","email":"trogers4@xrea.com"},
{"id":6,"first_name":"Rebecca","email":"rpeterson5@mlb.com"},
{"id":7,"first_name":"Chris","email":"cbailey6@yellowpages.com"},
{"id":8,"first_name":"Howard","email":"hbailey7@miibeian.gov.cn"},
{"id":9,"first_name":"Sara","email":"ssimpson8@techcrunch.com"},
{"id":10,"first_name":"Lois","email":"lmartinez9@dion.ne.jp"},
{"id":11,"first_name":"Jeffrey","email":"jhalla@intel.com"},
{"id":12,"first_name":"Teresa","email":"tcampbellb@usnews.com"},
{"id":13,"first_name":"Susan","email":"skingc@wired.com"},
{"id":14,"first_name":"Richard","email":"rpattersond@omniture.com"},
{"id":15,"first_name":"Ronald","email":"rgreenee@wordpress.org"}]

我想再添加一个元素,但我无法弄清楚如何。 我有以下节点代码:

var jsonfile = require('jsonfile');
var util = require('util');

var file = 'data.json';
var jsonObj = {};
jsonfile.readFile(file, function(err, obj) {
    jsonObj = obj;

    new_obj = {"id":16,"first_name":"Florin","email":"popflorin1705@yahoo.com"};
    //jsonObj.push(new_obj)
    console.log(typeof jsonObj);

    /*jsonfile.writeFile(file, jsonObj, function (err) {
      console.error(err)
    })*/
});

我尝试使用push方法,但显然不起作用,因为它是一个对象而不是一个数组,即使它看起来像一个数组。哪个是在对象末尾添加另一行的好方法(或数组 - 我很困惑)?

2 个答案:

答案 0 :(得分:3)

我相信你忘了解析JSON。阅读完文件后,您的代码应为:

jsonObj = JSON.parse(obj);

而不是直接分配。

答案 1 :(得分:1)

声明变量

 var new_obj = {"id":16,"first_name":"Florin","email":"popflorin1705@yahoo.com"};

然后使用push()已经完成了。试试看。仅当obj是json对象时,它才会起作用。