0

My question is related to this question jQuery.parseJSON single quote vs double quote. There are many topics on this issue, but I still don't know clean solution.

I dont have Jquery, and I am working in TypeScript (not JavaScript). But everythink else is same.

My question is: What if I have string with double qoute ?

How to resolve this problem ? Is there way to convert this in valid string type?

var obj = JSON.parse(data);

I will get error if json string is with double qoute.

SyntaxError: Unexpected token

Whole code is:

fs.readFile(templatePath, 'utf8', (err: Error, data: Object) => {
    if (err) {
        res.send(500);
    }

    try {
        var obj = JSON.parse(data);
        res.json(obj);
    } catch (e) {
        res.send(500);
    }
});

Thanks for help.

Community
  • 1
  • 1
Raskolnikov
  • 3,791
  • 9
  • 43
  • 88

3 Answers3

2

Before storing your string into JSON replace all instances of " with \"

var str='hello "Rajat Bhardwaj"';
str=str.replace(/"/g,'\\"');
// Now push it into JSON
waders group
  • 538
  • 3
  • 7
1

You need to replace all occurences of a single quote in your string. You can do this by simply using the String.replace() function.

You could write a single function which is reusable if you need it elsewhere like that:

function replaceAll(find, replace, str) {
  return str.replace(new RegExp(find, 'g'), replace);
}

and call it like that:

var str = replaceAll("'", "\"", data);
var obj = JSON.parse(str);

For more informations, check this answer: Replacing all occurrences of a string in JavaScript

Community
  • 1
  • 1
B. Kemmer
  • 1,517
  • 1
  • 14
  • 32
0

You need to escape quotes with a backslash \"blah blah \" or write your custom sanitizer.

data = '{\"text\": \"This is json string with double quotes\"}' . 

A backslash in front of a double quote makes it part of a string and not a special character. This is called escaping a character.

chabislav
  • 939
  • 1
  • 8
  • 27
  • How to escape quotes? Can you write example? – Raskolnikov Jul 09 '15 at 06:31
  • Assume your `data = '{\"text\": \"This is json string with double quotes\"}'` . Backslash in front of a double quote makes it part of a string and not a special character. – chabislav Jul 09 '15 at 06:36