I get a string with the following output from json_encode
:
["images\/zara\/shoes\/thumbnail",
"images\/hermes\/shoes\/thumbnail",
"images\/hermes\/shoes\/thumbnail"]
I attempt to parse it with the below code, but it gives me an error:
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 );`
How do I prevent this?
$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>";
}
Try This.
It's not because of backslashes. JSONLint parses it correctly. It's because JSON.parse() must have string parameter and you are passing an array. 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);
Also mentioned here: JSON.parse unexpected character error.
Example:
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
I suspect there's an AJAX call somewhere in the omitted code. jQuery AJAX methods decode JSON strings for you, so JSON.parse()
is not necessary.