英文:
How add an Object to this JSON in Javascript?
问题
{
"user1": { "id": 1, "nVote": 0, "comment": "" },
"user2": { "id": 2, "nVote": 1, "comment": "test" }
}
英文:
I have this JSON in a File:
{
"user1": {
"id": 1,
"nVote": 0,
"comment": ""
}
}
And I would like to add an object user2 with the same parameters and corresponding values.
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);
that result:
[
{ id: 1, nVote: 0, comment: '' },
[ user2: { id: 2, nVote: 1, comment: 'test' } ]
]
But I would like to ultimately this result:
{
"user1": { id: 1, nVote: 0, comment: '' },
"user2": { id: 2, nVote: 1, comment: 'test' }
}
答案1
得分: 0
如果您想要的结果是一个对象,就不需要将它转换为数组。只需向对象添加属性。
const obj = JSON.parse(fs.readFileSync('./datei.json', 'utf8'));
obj['user2'] = {
"id": 2,
"nVote": 1,
"comment": 'test'
};
英文:
If the result you want is an object, there's no need to convert it to an array. Just add a property to the object.
const obj = JSON.parse(fs.readFileSync('./datei.json', 'utf8'));
obj['user2'] = {
"id": 2,
"nVote": 1,
"comment": 'test'
};
答案2
得分: 0
你只需将JSON对象视为数组
简单
考虑这个
```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文件中
<details>
<summary>英文:</summary>
all you have to do is to treat the json object as array
simply
consider this
```json
[
{user1:{"id":2,"nVote":1,...}}
{user2:{"id":2,"nVote":1,...}}
]
so
const obj = []
obj.push({user1:{id:2,nVote:2})
obj.push(({user2:{id:3,nVote:1})
that's all you need then you can store that using the fs to extract it to a json file
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论