我在文件中有这个 JSON:
{
"user1": {
"id": 1,
"nVote": 0,
"comment": ""
}
}
我想添加一个具有相同参数和相应值的对象 user2 。
function json2Array(json) {
var result = [];
var keys = Object.keys(json);
keys.forEach(function (key) {
result.push(json[key]);
});
return result;
}
const fs = require('fs');
const obj = JSON.parse(fs.readFileSync('./datei.json', 'utf8'));
const arObj = json2Array(obj);
let user = [];
user['user2'] = {
"id": 2,
"nVote": 1,
"comment": 'test'
};
arObj.push(user);
结果:
[
{ id: 1, nVote: 0, comment: '' },
[ user2: { id: 2, nVote: 1, comment: 'test' } ]
]
但我希望最终得到这个结果:
{
"user1": { id: 1, nVote: 0, comment: '' },
"user2": { id: 2, nVote: 1, comment: 'test' }
} Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
你所要做的就是将 json 对象视为数组
简单
考虑一下
[ {user1:{"id":2,"nVote":1,...}} {user2:{"id":2,"nVote":1,...}} ]所以
const obj = [] obj.push({user1:{id:2,nVote:2}) obj.push(({user2:{id:3,nVote:1})这就是您所需要的,然后您可以使用 fs 将其提取到 json 文件进行存储
如果你想要的结果是一个对象,则无需将其转换为数组。只需向对象添加一个属性即可。
const obj = JSON.parse(fs.readFileSync('./datei.json', 'utf8')); obj['user2'] = { "id": 2, "nVote": 1, "comment": 'test' };