2012-01-09 309 views
1

我得到以下输出的字符串从json_encodejson_encode的输出()含有斜线的字符串不能被JSON.parse(解析)

["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);` 

如何避免这种情况?

回答

0
$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>"; 
} 

试试这个。

+1

代码不起作用 – sajid 2012-01-09 06:40:47

+0

@sajid:有错误? – 2012-01-09 07:18:40

1

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

To convert a JSON string into a JavaScript object, you simply pass the JSON into the JSON.parse() method, like this:

var jsObject = JSON.parse(jsonString);

这里也提到:JSON.parse unexpected character error

例子:

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 
0

我怀疑有一个AJAX调用某处省略代码。 jQuery AJAX方法为你解码JSON字符串,所以JSON.parse()是没有必要的。