Как удалить невидемый символ в JSON?
Есть файл в нем массив JSON :
{
"title": "Exploring the Use and Impact of Opioids and Stimulants in the U.S.",
"text": "Opioids and stimulants continue to pose significant challenges in the United States. According to the National Institute on Drug Abuse (NIDA), in 2019, an estimated 10.1 million people aged 12 or older misused opioids, and 5.9 million people misused stimulants. The misuse of these substances can lead to addiction, overdose, and other serious health issues. It's crucial to understand these statistics and the factors contributing to drug misuse to develop effective prevention and treatment strategies.
Opioids, which include prescription pain relievers, heroin, and fentanyl, accounted for 69,550 overdose deaths in 2020, a 38.4% increase from 2019. Stimulants, such as cocaine and methamphetamine, were involved in 23,645 overdose deaths in 2020, a 35.4% increase from 2019. These numbers underscore the urgent need for intervention and support for those struggling with substance use disorders.
",
"comment": "The misuse of opioids and stimulants is a growing concern in the U.S., with a significant increase in overdose deaths. This article explores the statistics and the importance of understanding these issues for effective prevention and treatment. #OpioidMisuse #StimulantMisuse #DrugAbuseStatistics #OverdosePrevention"
},
В JSON попадаются переносы строк которые я не могу заменить , потому что не могу определить что это за символ, вручную менять миллион строк не очень хочется )
Из за чего получаю ошибку "Bad control character in string literal in JSON at position 220150 (line 1537 column 514)"
Как привести к правильному формату все обьекты ?
{
"title": "Exploring the Use and Impact of Opioids and Stimulants in the U.S.",
"text": "Opioids and stimulants continue to pose significant challenges in the United States. According to the National Institute on Drug Abuse (NIDA), in 2019, an estimated 10.1 million people aged 12 or older misused opioids, and 5.9 million people misused stimulants. The misuse of these substances can lead to addiction, overdose, and other serious health issues. It's crucial to understand these statistics and the factors contributing to drug misuse to develop effective prevention and treatment strategies.
Opioids, which include prescription pain relievers, heroin, and fentanyl, accounted for 69,550 overdose deaths in 2020, a 38.4% increase from 2019. Stimulants, such as cocaine and methamphetamine, were involved in 23,645 overdose deaths in 2020, a 35.4% increase from 2019. These numbers underscore the urgent need for intervention and support for those struggling with substance use disorders.",
"comment": "The misuse of opioids and stimulants is a growing concern in the U.S., with a significant increase in overdose deaths. This article explores the statistics and the importance of understanding these issues for effective prevention and treatment. #OpioidMisuse #StimulantMisuse #DrugAbuseStatistics #OverdosePrevention"
}
Ответы (1 шт):
"Невидимые символы" это символы переноса строк. За перенос строки отвечают символы:
Название | Символ | Dec | Hex | Oct |
---|---|---|---|---|
Перенос строки | LF \n | 10 | 0a | 012 |
Возврат каретки | CR \r | 13 | 0d | 015 |
В зависимости от ОС символы перевода строк могут идти в последовательности CRLF, CR, LF.
Для того, что бы заменить все символы переноса строк, можно воспользоваться регулярным выражением и методом строк replace для их замены.
import fs from 'fs'
// Читаем файл
let file = fs.readFileSync('jsons/tst.json', 'utf8');
// Меняем все переносы строк
file = file.replace(/(?:\r\n|\r|\n)/g, '');
// Парсим в JSON
const json = JSON.parse(file);
Пример для демонстрации без чтения данных из файла:
const textFromFile = `{
"text": "Opioids and stimulants continue to pose significant challenges in the United States. According to the National Institute on Drug Abuse (NIDA), in 2019, an estimated 10.1 million people aged 12 or older misused opioids, and 5.9 million people misused stimulants. The misuse of these substances can lead to addiction, overdose, and other serious health issues. It's crucial to understand these statistics and the factors contributing to drug misuse to develop effective prevention and treatment strategies.
Opioids, which include prescription pain relievers, heroin, and fentanyl, accounted for 69,550 overdose deaths in 2020, a 38.4% increase from 2019. Stimulants, such as cocaine and methamphetamine, were involved in 23,645 overdose deaths in 2020, a 35.4% increase from 2019. These numbers underscore the urgent need for intervention and support for those struggling with substance use disorders.
"}`;
const fileFromVar = JSON.parse(textFromFile.replace(/(?:\r\n|\r|\n)/g, ''));
console.log(fileFromVar.text);