1

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?

Jeremy
  • 1
  • 85
  • 340
  • 366
sajid
  • 247
  • 7
  • 15

3 Answers3

1

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
Community
  • 1
  • 1
BartekR
  • 3,827
  • 3
  • 24
  • 33
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>";
}

Try This.

Muthu Krishnan
  • 1,664
  • 2
  • 10
  • 15
0

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.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360