简体   繁体   中英

JSON.parse error when in text is present \' or \"

In PHP I use mysql_real_escape_string that transforms symbol ``' and " to \\' and \\"

After, I extract data from MySQL and use it in JavaScript as JSON.

For example, the b' is transformed to b\\' , and in JavaScript I have these errors:

var a='{"a":"b\'"}';
var b=JSON.parse(a);
alert(b.a);

var a='{"a":"b\""}';
var b=JSON.parse(a);
alert(b.a);

/*
Exception: JSON.parse: expected ',' or '}' after property value in object at line 1 column 9 of the JSON data
*/

If you are looking to include the quote in the JSON String, add an addition \\ .

Example

 var a = '{"a":"b\\'"}'; var b = JSON.parse(a); alert(ba); var a = '{"a":"b\\\\""}'; var b = JSON.parse(a); alert(ba); 

Remove extra quote from this line var a='{"a":"b\\""}';

Modified Code:

var a='{"a":"b\"}';
var b=JSON.parse(a);
alert(b.a);
var a='{"a":"b\'"}';  //or you can use "{\"a\":\"b'\"}";
var b=JSON.parse(a);
alert(b.a);

This works because the value stored in variable a is {"a":"b'"}

var a='{"a":"b\\""}';    //or you can use "{\"a\":\"b\\\"\"}";
var b=JSON.parse(a);
alert(b.a);

For this case the value stored in variable a is {"a":"b\\""}

You can try to construct the string that the JSON should look like by constructing the object and stringify it like so:

var a = { "a" : "b'" };
console.log(JSON.stringify(a));

After you extract data from MySQL, use stripslashes() to strip the extra backslashes. And then encode the data as JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM