[英]JSON.parse error when in text is present \' or \"
In PHP I use mysql_real_escape_string
that transforms symbol ``' and "
to \\'
and \\"
在PHP中,我使用
mysql_real_escape_string
将符号``'和"
为\\'
和\\"
\\'
After, I extract data from MySQL and use it in JavaScript as JSON. 之后,我从MySQL提取数据并将其在JavaScript中用作JSON。
For example, the b'
is transformed to b\\'
, and in JavaScript I have these errors: 例如,
b'
被转换to b\\'
,在JavaScript中,我有以下错误:
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 \\
. 如果要在JSON字符串中包含引号,请添加一个
\\
。
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\\""}';
从此行中删除多余的引号
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'"}
之所以有效,是因为存储在变量
a
值为{"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\\""}
对于这种情况,存储在变量
a
值为{"a":"b\\""}
You can try to construct the string that the JSON should look like by constructing the object and stringify it like so: 您可以尝试通过构造对象并按如下所示对其进行字符串化来构造JSON外观应为的字符串:
var a = { "a" : "b'" };
console.log(JSON.stringify(a));
After you extract data from MySQL, use stripslashes() to strip the extra backslashes. 从MySQL提取数据后,使用stripslashes()去除多余的反斜杠。 And then encode the data as JSON.
然后将数据编码为JSON。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.