EaBengaluru
EaBengaluru

Reputation: 71

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!!!

Upvotes: 3

Views: 4088

Answers (3)

MHY
MHY

Reputation: 1

I used Gabriel Rodríguez Flores's solution, but added double quotes:

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

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

Upvotes: 0

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 \"

Upvotes: 1

Milad Aghamohammadi
Milad Aghamohammadi

Reputation: 1976

this is your solution

var fs = require('fs');
var path = require('path');
var fileLoc = path.join(__dirname,'file.json');
var content = fs.readFileSync(fileLoc,'utf8');
content = content.replace(/\\/g, '\\\\')
content = JSON.parse(filecontent);

When you want parse a string that contain backslash character, you should change every backslash with two backslash. below is an example run in console tab of chrome browser

content = '{"path":"R:\\30-09-18\\LTP\\p"}'
JSON.parse(content)
VM835:1 Uncaught SyntaxError: Unexpected number in JSON at position 12
    at JSON.parse (<anonymous>)
    at <anonymous>:1:6
(anonymous) @ VM834:1
content = content.replace(/\\/g, '\\\\')
"{"path":"R:\\30-09-18\\LTP\\p"}"
JSON.parse(content)
//result is {path: "R:\30-09-18\LTP\p"}

Upvotes: 0

Related Questions