I have a problem appending data in my .json file. So I searched this problem and found a lot of results, but it doesn't work for me. If there is a library for comfort appending data in json file or just fix my code I will be grateful
Here is my function
function writeToJson(path: string, data: any, rewrite: boolean = false)
{
let old_data: any = fs.readFileSync(path)
if(old_data.length == 0 || rewrite == true)
{
fs.writeFileSync(path, JSON.stringify(data, null, 4))
return
}
let json_obj: any = [JSON.parse(old_data)] // without brackets it reverts an error
json_obj.push(data)
fs.writeFileSync(path, JSON.stringify(json_obj, null, 4))
}
and bellow is actual result .json
[
[
[
[
[
{
"price": 0.5631746759368121,
"timestamp": "5/4/2022, 2:06:44 AM"
},
{
"price": 0.5631746759368121,
"timestamp": "5/4/2022, 2:06:53 AM"
}
],
{
"price": 0.5631746759368121,
"timestamp": "5/4/2022, 2:06:55 AM"
}
],
{
"price": 0.5631746759368121,
"timestamp": "5/4/2022, 2:06:58 AM"
}
],
{
"price": 0.5631746759368121,
"timestamp": "5/4/2022, 2:07:01 AM"
}
],
{
"price": 0.5631746759368121,
"timestamp": "5/4/2022, 2:07:04 AM"
}
]
As a result I expect something like
{
{
"price": 0.5631746759368121,
"timestamp": "5/4/2022, 2:07:04 AM"
}
{
"price": 0.5631746759368121,
"timestamp": "5/4/2022, 2:07:04 AM"
}
...
{
"price": 0.5631746759368121,
"timestamp": "5/4/2022, 2:07:04 AM"
}
}
CodePudding user response:
You probably just miss to specify the encoding:
fs.readFileSync(path, "utf8")
Node.js doc of fs.readFileSync
:
If the
encoding
option is specified then this function returns a string. Otherwise it returns a buffer.
So now you should be able to use it as expected:
interface Data {
price: number;
timestamp: string;
}
let old_data: string = fs.readFileSync(path, "utf8")
// ...
let json_obj: Data[] = JSON.parse(old_data) || [] // No longer need extra array; initialoze as an empty array if needed
json_obj.push(data)
CodePudding user response:
The problem was in .json file not in a function. So if you want your script works fine
function writeToJson(path: string, data: any, rewrite: boolean = false)
{
let old_data: any = fs.readFileSync(path)
if(old_data.length == 0 || rewrite == true)
{
fs.writeFileSync(path, JSON.stringify(data, null, 4))
return
}
let json_obj: any = [JSON.parse(old_data)] // without brackets it reverts an error
json_obj.push(data)
fs.writeFileSync(path, JSON.stringify(json_obj, null, 4))
}
make sure that your json file already starts with brackets
[
// empty or some data
]