javascript 将数据添加到现有的 json 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32940713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add data to existing json object
提问by Darkrum
So what i'm trying to achieve is creating a json
flat file to store user info where i'm stuck is that i don't know how to add new nested objects that are empty and then save the json file and reload it.
所以我想要实现的是创建一个json
平面文件来存储我卡住的用户信息,因为我不知道如何添加新的空嵌套对象,然后保存 json 文件并重新加载它。
what i have in my *json*
file is this.
我的*json*
档案里有这个。
{
"users" : {
"test" : {
},
"test1" : {
}
}
}
I'm trying to add as many new objects as i want to it. So for example.
我正在尝试添加任意数量的新对象。所以例如。
{
"users" : {
"test" : {
},
"test1" : {
},
"test2" : {
},
"test3" : {
}
}
}
My server side Javascript
我的服务器端 Javascript
json.users.push = username;
fs.writeFile("./storage.json", JSON.stringify(json, null, 4) , 'utf-8');
delete require.cache[require.resolve('./storage.json')];
json = require("./storage.json");
With this code it does not write the file so when the require is done i end up with the same file and my json object ends up like this when i console.log it
使用此代码,它不会写入文件,因此当要求完成时,我最终会得到相同的文件,而当我使用 console.log 时,我的 json 对象会像这样结束
{
"users": {
"test": {},
"test1": {},
"push": "test2"
}
}
Please do not recommend some external module to solve something has simple as this. Also if any one can point me to a in depth json documentation that gets straight to the point with what i'm try to do it would be appreciated
请不要推荐一些外部模块来解决像这样简单的事情。此外,如果有人可以向我指出深入的 json 文档,该文档可以直接说明我正在尝试做的事情,我将不胜感激
采纳答案by Thank you
Use []
to access a dynamic key on the object
使用[]
访问对象的动态密钥
json.users[username] = {a: 1, b: 2}
Be careful naming your variable like that tho because json
the way you're using it is not JSON. JSON is a string, not an object with keys.
小心这样命名你的变量,因为json
你使用它的方式不是 JSON。JSON 是一个字符串,而不是一个带有键的对象。
See the below demo for distinction
区别请看下面的demo
var json = '{"users":{"test1":{},"test2":{}}}';
var obj = JSON.parse(json);
var newuser = 'test3';
obj.users[newuser] = {};
console.log(JSON.stringify(obj));
//=> {"users":{"test1":{},"test2":{},"test3":{}}}