7

I'm trying to parse a JSON encoded string from a cookie and when I run json_decode() on the string it returns as null. It should be a simple operation - what am I missing?

/* Get */

    $cookie_exampleData = $_COOKIE['exmaple_data'];

    // Retrieves: '{\"FirstName\":\"Angus\",\"LastName\":\"MacGyver\",\"Email\":\"hello@email.com\",\"Phone\":\"8185555555\"}'

/* Decode */

    $cookie_exampleData_decoded = json_decode($cookie_exampleData);

/* Print */

    var_dump($cookie_exampleData_decoded);

    // Returns: NULL
technopeasant
  • 7,809
  • 31
  • 91
  • 149
  • `\"` makes your JSON invalid – kero Jan 18 '15 at 23:32
  • @kingkero that's what print_r()'s printing. I don't have access to the system that's creating the cookie, but in a nutshell it's running json_encode() on an array and setting that string as the cookie's value. – technopeasant Jan 18 '15 at 23:36
  • it occurs that using `stripslashes` is common when reading from `$_GET`, `$_POST`, `$_COOKIE`. `JSON.stringify` indeed converts `{1:2}` into `"{\"1\":2}"` which is seamless inside same language but not in transport – Hebe May 26 '23 at 08:45

1 Answers1

19

In this case, you need remove escaped quotes:

$cookie_exampleData = stripslashes($_COOKIE['exmaple_data']);

See stripslashes

voodoo417
  • 11,861
  • 3
  • 36
  • 40
  • Thanks. I don't know anything about anything, so judging from @kingkero's comment above it seems odd that I have to unescape a JSON encoded string - shouldn't decoding handle that? – technopeasant Jan 19 '15 at 00:16
  • I would also like an answer to this question. – mike_freegan Jun 23 '19 at 11:24
  • @mike_freegan Because from the OP`s question we see "strange" JSON-format ( with slashes ) => therefore before decoding we have to remove those slashes. – voodoo417 Jul 10 '19 at 16:57
  • 2
    @technopeasant "shouldn't decoding handle that" => no, it shouldnt escape slashes. It`s not valid JSON. – voodoo417 Jul 10 '19 at 16:58