help me pls . I write several arrays to a txt file, and then I want to parse them, what am I doing wrong
fs.readFile("./data.txt", "utf8",
function(error,dataRes){
console.log('Читаю данные')
if(error) throw error;
data = JSON.parse('['+dataRes+']'.replace(/\]\[/g,'],['));
console.log(data)
createitem();
});
data.txt(example)
[{"update":"Сегодня, 14:44"},{"update":"Сегодня, 14:43"},{"update":"Сегодня, 14:31"}][{},{},{},{"link":"https://www.doska.by//msg/animals/cats/maine-coon/bdnkh.html"}]
this works but you really should fix the data.txt
const dataRes = `[{"update":"Сегодня, 14:44"},{"update":"Сегодня, 14:43"},{"update":"Сегодня, 14:31"}][{},{},{},{"link":"https://www.doska.by//msg/animals/cats/maine-coon/bdnkh.html"}]`
const obj = JSON.parse(`[${dataRes.replaceAll("][","],[")}]`).flat(); // remove .flat() if you want two arrays
console.log(obj)
Your problem is this string:
'['+dataRes+']'.replace(/\]\[/g,'],[')
The replace call is only applied to ']', not to '['+dataRes+']'. It tries to replace all occurrences of ][ in the string ']'.
You can fix your error with parenthesis:
fs.readFile("./data.txt", "utf8",
function(error,dataRes){
console.log('Читаю данные')
if(error) throw error;
data = JSON.parse(('['+dataRes+']').replace(/\]\[/g,'],['));
console.log(data)
createitem();
});
This replaces all occurrences of ][ in the string '['+dataRes+']'.
Example:
const dataRes = `[{"update":"Сегодня, 14:44"},{"update":"Сегодня, 14:43"},{"update":"Сегодня, 14:31"}][{},{},{},{"link":"https://www.doska.by//msg/animals/cats/maine-coon/bdnkh.html"}]`;
const data = JSON.parse(('['+dataRes+']').replace(/\]\[/g,'],['));
console.log(data);
you have to fix data.txt
var dataTxtStr='[{"update":"Сегодня, 14:44"},{"update":"Сегодня, 14:43"},{"update":"Сегодня, 14:31"}][{},{},{},{"link":"https://www.doska.by//msg/animals/cats/maine-coon/bdnkh.html"}]';
var dataTxt= JSON.parse(dataTxtStr.replaceAll("}][{","},{"));