Javascript 如何插入JSON?
我应该如何在JSON中插入一些数据 我需要通过脚本创建一个JSON文件。JSON文件应如下所示:Javascript 如何插入JSON?,javascript,json,Javascript,Json,我应该如何在JSON中插入一些数据 我需要通过脚本创建一个JSON文件。JSON文件应如下所示: { "index": { "colors": [ { "title": "great color", "name": "nice color" }, { "title": "worst color",
{
"index": {
"colors": [
{
"title": "great color",
"name": "nice color"
},
{
"title": "worst color",
"name": "bad color"
}
]
}
}
fs.writeFile(file, JSON.stringify(posts, null, 2));
{
"colors": [
{
"title": "great color",
"name": "nice color"
},
{
"title": "worst color",
"name": "bad color"
}
]
}
在我的javascript文件中,我可以推送到颜色数组:
var index = {index: {}};
var posts = {colors: []};
var single = {title: "great color", name: "nice color"};
posts.colors.push(single);
但是,如何将其插入索引对象中?我当前正在写入一个JSON文件,如下所示:
{
"index": {
"colors": [
{
"title": "great color",
"name": "nice color"
},
{
"title": "worst color",
"name": "bad color"
}
]
}
}
fs.writeFile(file, JSON.stringify(posts, null, 2));
{
"colors": [
{
"title": "great color",
"name": "nice color"
},
{
"title": "worst color",
"name": "bad color"
}
]
}
但这只写入颜色数组,生成的JSON文件如下所示:
{
"index": {
"colors": [
{
"title": "great color",
"name": "nice color"
},
{
"title": "worst color",
"name": "bad color"
}
]
}
}
fs.writeFile(file, JSON.stringify(posts, null, 2));
{
"colors": [
{
"title": "great color",
"name": "nice color"
},
{
"title": "worst color",
"name": "bad color"
}
]
}
如何创建所需的JSON结构?您可以将颜色数组添加到索引对象中:
var obj = {}; // basic object
obj['index'] = {}; // The index child object
obj.index['colors'] = new Array(); // the color array below index
var single = {title: "great color", name: "nice color"};
obj.index.colors.push(single);
现在我可以写我自己的答案了,试试这个:
var obj = {
index: {
colors: []
}
}, // basic object
single = {
title: "great color",
name: "nice color"
};
obj.index.colors.push(single);
// ...
fs.writeFile(file, JSON.stringify(obj, null, 2));
我不知道为什么你需要单独制作对象,但我只是假设你在其他地方添加颜色的索引,所以我把它分开了。这样就不那么冗长了。请在这里发布您的代码。你真的需要我们打开三个不同的页面来理解你在说什么吗?!对不起,我不知道我可以把它都贴在这里!Tyr回答得很好,谢谢你,因为我不能写我自己的答案,因为问题被搁置,我将在这里发表评论。这将更加简洁: