2

I cannot make json_decode() to work when the string value contains single quote (') as example below:

$result = "{\"message\":\"test \' \",\"report\":[{\"1\":[{\"port\":\"gsm-1.2\",\"phonenumber\":\"XXXXXXXXXXX\",\"time\":\"2016-08-31 00:22:57\",\"result\":\"success\"}]}]}";
$resp = json_decode($result, true);
echo $resp;
Bootsector
  • 35
  • 1
  • 7
  • http://stackoverflow.com/questions/8832528/escaping-encoding-single-quotes-in-json-encoded-html5-data-attributes – Linesofcode Aug 30 '16 at 17:03
  • 2
    Why are you escaping it? Just use `'`. Also, you can't `echo` the array. – AbraCadaver Aug 30 '16 at 17:04
  • 1
    And don't build JSON strings by hand if you don't have to. Build the correct object/array and then let `json_encode()` handle the rest. – Sammitch Aug 30 '16 at 17:05
  • @AbraCadaver you are right. the escaping of the single quote causes the problem. – Bootsector Aug 30 '16 at 17:18
  • @Sammitch I don't realy build it by hand. the result came from a result from our gsm gateway api. but that specific string values causes the error of json_decode. but abracadaver pointed out it's the escaping of single quote. – Bootsector Aug 30 '16 at 17:21

2 Answers2

2

Your $result json is not in proper format so i think you need to use stripslashes() to format it and after use json_decode(). it would work :).

<?php
$result = "{\"message\":\"test \'\",\"report\":[{\"1\":[{\"port\":\"gsm-1.2\",\"phonenumber\":\"XXXXXXXXXXX\",\"time\":\"2016-08-  31 00:22:57\",\"result\":\"success\"}]}]}";
$result=stripslashes($result);
$resp = json_decode($result, true);
var_dump($resp);
?>

check on phpfiddle => http://phpfiddle.org/main/code/4e7n-vjxa

Abhijit Jagtap
  • 2,740
  • 2
  • 29
  • 43
1

In your code the single quote(') is skipped with slash () thus it is breaking the JSON format.

Try removing the slash and try. It should work.

You should check the code where you are generating this JSON.

Vivek Srivastava
  • 569
  • 4
  • 13