views:

238

answers:

2

Does anyone know why this happens?

var_dump(json_decode(stripslashes(json_encode(array("O'Reiley"))))); // array(1) { [0]=> string(8) "O'Reiley" } 
var_dump(json_decode(stripslashes(json_encode(array("O\'Reiley"))))); // NULL

Are ' used at all by the JSON functions?

+4  A: 

I don't know for sure, but json_last_error() should :)

My guess, though, is that json_encode() does something to the \' that the stripslashes() then breaks - e.g. add another "\" to escape the backslash.

Isn't fiddling with a json encoded string using striplslashes() before it's decoded wrong anyway?

Pekka
First time I'm gonna use that function! Yey!
Alix Axel
Returns JSON_ERROR_SYNTAX, still I don't understand why...
Alix Axel
Can you dump the json_encoded string from the second line (without stripslashes)?
Pekka
You're right: `["O\\'Reiley"]` could have just ignored it since it uses `"` and not `'`. There goes my super cool anti magic quotes method. =(
Alix Axel
+1  A: 

I didn't look at it too deeply, but it looks like your code is

  1. Taking a PHP Array and turning it into a json string

  2. Mucking with that string

  3. Trying to decode the mucked string as json

Think of it like this

$json_string = json_encode(array("O\'Reiley");
$json_string = stripslashes($json_string);      

//it's no longer json, its just some random non-conforming string
var_dump(json_decode($json_string))
Alan Storm
Yeah, my though was that JSON didn't used `'` and thus had no reason to escape it. I was wrong.
Alix Axel