javascript - JSON类数组对象,添加项目

标签 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"}]

我想向其中添加一个元素,但我不知道如何添加。 我有以下 Node 代码:

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

最佳答案

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

jsonObj = JSON.parse(obj);

而不是直接赋值。

关于javascript - JSON类数组对象,添加项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35140413/

相关文章:

javascript - 使用 css 显示和 JS 将图像替换为另一个图像

javascript - HTML CSS JS 波浪绘制和动画

javascript - Bootstrap 4 导航下拉悬停在桌面上/点击移动设备

javascript - 限制数组大小

c - 数组未正确填充

objective-c - NSURLConnection 在 GET 时提前关闭

json - 在 SQLite 中使用 JSON1 有什么好处?

javascript - 晦涩的 JavaScript 错误 b(e.target).zIndex is not a function 是什么意思?

javascript - 如何防止将值两次插入数组? (jQuery)

jQuery ajax 调用返回 WordPress 中的 301 永久移动错误