【问题标题】:How to push JS object to JSON in new line?如何在新行中将 JS 对象推送到 JSON?
【发布时间】:2015-01-17 08:17:11
【问题描述】:

如何修改此函数以在文件的新行中添加每个对象?

   exports.addWaypoint = function(id, type, param){
        var dataIn = fs.readFileSync('./markers.json');
        var obj = JSON.parse(dataIn);          
        obj.markers.push({
            "id": id,
            "type": type,
            "param": param,
        });           
        writeJson(obj);    
    }

【问题讨论】:

标签: javascript json node.js file


【解决方案1】:

这可能与Javascript: How to generate formatted easy-to-read JSON straight from an object? 重复

这里有一个快速的答案:使用带有可选参数的 JSON.stringify 来指示每个嵌套元素的缩进。

var o = {
    "id": 123,
    "type": "good",
    "param": { name: "Fred", age: 24 },
};

console.log( JSON.stringify(o,null,4) );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2018-02-07
    • 2019-02-21
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多