W
W
Windyay2022-04-10 21:55:10
JSON
Windyay, 2022-04-10 21:55:10

How to record data correctly?

How to write data correctly
I write
fs.appendFile('./data.txt', JSON.stringify(data));
And so several times, as a result I have several arrays in the date file,
then I want to get them
data = JSON.parse (result)
as a result I get

}, {
  "update": "11:09"
}][{
  "update": "Сегодня, 21:45"
}, {

an error (this is with jsonlint) that I don’t have enough commas between arrays (which is logical)
Therefore, I get an
unexpected token
error , everything is logical, but I don’t understand how to fix it
How can I write an array separated by a comma, or how can I parse invalid JSON

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
dollar, 2022-04-10
@Windyay

Like a crutch, but in most cases it will work: You can also do this:
data = JSON.parse(result.replace(/\]\[/g,'],['));
data = JSON.parse(result.split('][').join('],['));

T
TheAndrey7, 2022-04-10
@TheAndrey7

appendFile()suitable for simple text files, such as logs.
In the case of JSON, you need:

  1. Read file content
  2. Parse it to JSON
  3. Make the necessary changes (add elements)
  4. Save modified JSON to a file by completely overwriting the file

If you do not want to do this manually, you need to look towards databases.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question