【问题标题】:JSON array-like object, add itemJSON 类数组对象,添加项
【发布时间】:2016-02-01 21:11:25
【问题描述】:

我有一个 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 方法,但显然不起作用,因为它是一个对象而不是数组,即使它看起来像一个数组。在对象(或数组 - 我很困惑)末尾添加另一行的好方法是什么?

【问题讨论】:

标签: javascript arrays json node.js


【解决方案1】:

我相信您忘记解析 JSON。阅读文件后,您的代码应该是:

jsonObj = JSON.parse(obj);

而不是直接赋值。

【讨论】:

  • undefined:1 [object Object],[object Object],[object Object],[object Object],[object Object ^ SyntaxError: Unexpected token o at Object.parse (native) at /home /florin17/Desktop/Work/Express/server/app.js:10:20 在 /home/florin17/Desktop/Work/Express/server/node_modules/jsonfile/index.js:20:5 在 fs.js:268: 14 在 Object.oncomplete (fs.js:107:15)
【解决方案2】:

声明变量

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

然后使用push(),就像你已经完成的那样。试试看。仅当 obj 是您提到的 json 对象时,它才会起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 2012-08-21
    • 1970-01-01
    • 2015-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多