【发布时间】:2022-01-31 01:56:10
【问题描述】:
我的项目/文件夹
中有 3 个 Json 文件file1.json
{
"id":"01",
"name":"abc",
"subject":[
"subject1":"Maths",
"subject2":"Science"
]
}
文件2.json
{
"id":"01",
"name":"dummy",
"Degree":[
"Graduation":"BCom",
"Post Graduation":"MBA"
]
}
文件3.json
{
"id":"BA01",
"Address":"India",
"P Address":[
"State":"MP",
"City":"Satna"
]
}
我写了一个代码,我可以在其中读取我的 项目/文件夹,这样我就可以读取 json 文件中存在的所有数据并希望附加到我的 output.json
fs.readdir(
path.join(process.cwd(), "project/Folder"),
(err, fileNames) => {
if (err) throw console.log(err.message);
// Loop fileNames array
fileNames.forEach((filename) => {
// Read file content
fs.readFile(
path.join(
process.cwd(),
"project/Folder",
`${filename}`
),
(err, data) => {
if (err) throw console.log(err.message);
// Log file content
const output = JSON.parse(data);
fs.appendFile(
path.join(
process.cwd(),
"project/Folder",
`output.json`
),
`[${JSON.stringify(output)},]`,
(err) => {
if (err) throw console.log(err.message);
}
);
}
);
});
}
);
我的预期输出是这样的,因为我想在 output.json 中附加从 file1、file2、file3 json 获得的数据
[
{
file1.json data
},
{
file2.json data
},
{
file3.json data
}
]
但实际上我将其作为输出
[
{
file1.josn data
},
]
[
{
file2.josn data
},
]
[
{
file3.josn data
},
]
即使我正确编写了代码,我也不知道如何实现这样的预期输出,但我认为我遗漏了一些东西,但我不知道有人可以帮助我实现预期的代码吗?
[
{
file1.json data
},
{
file2.json data
},
{
file3.json data
}
]
【问题讨论】:
-
这是供您在本地机器上的个人日常使用还是应用程序的代码?如果它是为了您的特定个人用途,还有一个简单的替代方案,只需几行 bash 脚本。
-
你不能直接追加到一个 JSON 文件而不破解文件末尾的部分解析然后选择性覆盖(不推荐)。如果要追加,请使用 CSV 格式的文件,因为它是基于行的,您可以直接将行追加到文件中。要正确添加到 JSON,您必须将其全部读入内存,将其解析到数组中,将项目添加到数组中,然后将其恢复为 JSON 并将整个文件写回磁盘。 JSON 不适合直接在磁盘上进行修改。
-
这是一个应用程序@MImamPratama
标签: javascript node.js json nodes