如何使用逗号附加现有JSON文件","作为分隔符
anchors = [ { "title":" 2.0 Wireless " } ]
fs.appendFileSync('testOutput.json', JSON.stringify(anchors));
此当前代码的输出是这样的
[
{
"title":" 2.0 Wireless "
}
]
[
{
"title":" Marshall Major II "
}
]
如何使用逗号","以正确的格式获取此内容作为分隔符
我想得到这样的东西
[
{
"title":" 2.0 Wireless "
},
{
"title":" Marshall Major II "
}
]
答案 0 :(得分:3)
试试这个。不要忘记定义anchors
数组。
var data = fs.readFileSync('testOutput.json');
var json = JSON.parse(data);
json.push(...anchors);
fs.writeFile("testOutput.json", JSON.stringify(json))
答案 1 :(得分:-1)
我创建了两个小函数来处理要追加的数据。
示例:您想将数据 {“ title”:“ 2.0 Wireless”} 添加到同一文件夹根目录下的 my_data.json 文件中。只需调用 append_data(file_path,data),
如果文件存在,它将在JSON文件中追加数据。否则它将创建文件并向其中添加数据。
data = { "title":" 2.0 Wireless " }
file_path = './my_data.json'
append_data (file_path , data )
完整代码在这里:
const fs = require('fs');
data = { "title":" 2.0 Wireless " }
file_path = './my_data.json'
append_data (file_path , data )
async function append_data (filename , data ) {
if (fs.existsSync(filename)) {
read_data = await readFile(filename)
if (read_data == false) {
console.log('not able to read file')
}
else {
read_data.push(data)
dataWrittenStatus = await writeFile(filename, read_data)
if dataWrittenStatus == true {
console.log('data added successfully')
}
else{
console.log('data adding failed')
}
}
else{
dataWrittenStatus = await writeFile(filename, [data])
if dataWrittenStatus == true {
console.log('data added successfully')
}
else{
console.log('data adding failed')
}
}
}
async function readFile (filePath) {
try {
const data = await fs.promises.readFile(filePath, 'utf8')
return JSON.parse(data)
}
catch(err) {
return false;
}
}
async function writeFile (filename ,writedata) {
try {
await fs.promises.writeFile(filename, JSON.stringify(writedata,null, 4), 'utf8');
return true
}
catch(err) {
return false
}
}