Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove special characters before JSON.parse() while file reading

i have a json within a folder that comes from third party i don't have control on json data just i need to parse it and manipulate.

some time i will get this error:

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse

json is valid json but due to some special character i get above error:

R:\30-09-18\LTP\p

some time i will get parse error:

unable to parse .........

Question: how can i remove all special characters so that JSON.parse(data); will not throw any error

here is what i'm trying:

var fs = require('fs');
var path = require('path');
var fileLoc = path.join(__dirname,'file.json');
var content = fs.readFileSync(fileLoc,'utf8');
content = JSON.parse(filecontent);  // error occurs here

please help me thanks in advance!!!

like image 281
EaBengaluru Avatar asked Mar 15 '26 05:03

EaBengaluru


1 Answers

This is my workaround to replace special characters preserving them

const replacer = str => ({
  '\t': '\\t',
  '\n': '\\n',
  '\b': '\\b',
  '\r': '\\r',
  '\f': '\\f',
  '\\': '\\\\',
  '': '\\\\'
}[str]);

const regEx = new RegExp('\\\\|\t|\n|\b|\r|\f', 'g');

const replacedText = text.replace(regEx, replacer);
const object = JSON.parse(replacedText);

The only character I can't manage is \"

like image 94
Gabriel Rodríguez Flores Avatar answered Mar 17 '26 18:03

Gabriel Rodríguez Flores



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!