json_encode()的输出一个包含斜线的字符串可以';无法通过JSON.parse()进行解析


The output of json_encode() a string containing slashes can't be parsed by JSON.parse()

我从json_encode:得到一个具有以下输出的字符串

["images'/zara'/shoes'/thumbnail",
"images'/hermes'/shoes'/thumbnail",
"images'/hermes'/shoes'/thumbnail"]

我试图用下面的代码解析它,但它给了我一个错误:

var listofshoes = JSON.parse(data); 
for (var i in listofshoes) {
    $('#pgwrapid').append( $("<p>").text(listofshoes[i]));
}
ERROR: JSON.parse: unexpected character [Break On This Error] return window.JSON.parse( data );`

如何防止这种情况发生?

这不是因为反斜杠。JSONLint正确解析它。这是因为JSON.parse()必须有字符串参数,并且您正在传递一个数组。https://developer.mozilla.org/En/Using_native_JSON#Parsing_JSON.C2.A0strings

要将JSON字符串转换为JavaScript对象,只需将JSON转换为JSON.parse()方法,如下所示:

var jsObject = JSON.parse(jsonString);

这里还提到:JSON.parse意外的字符错误。

示例:

var data = ["images'/zara'/shoes'/thumbnail",
"images'/hermes'/shoes'/thumbnail",
"images'/hermes'/shoes'/thumbnail"];
data_string = JSON.stringify(data);
console.log(JSON.parse(data_string));    // no error
console.log(JSON.parse(data));           // will show error
$str    = '["images'/zara'/shoes'/thumbnail",
"images'/hermes'/shoes'/thumbnail",
"images'/hermes'/shoes'/thumbnail"]';
$rst    = json_decode($str);
//print_r($rst);
foreach($rst as $val) {
    echo $val;
    echo "<br>";
}

试试这个。

我怀疑遗漏的代码中有一个AJAX调用。jQueryAJAX方法为您解码JSON字符串,因此不需要JSON.parse()