开发者

Unable to decode JSON stripslashed String?

开发者 https://www.devze.com 2022-12-17 09:20 出处:网络
Does anyone know why this happens? var_dump(json_decode(stri开发者_StackOverflow中文版pslashes(json_encode(array(\"O\'Reiley\"))))); // array(1) { [0]=> string(8) \"O\'Reiley\" }

Does anyone know why this happens?

var_dump(json_decode(stri开发者_StackOverflow中文版pslashes(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?


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?


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))


You should try without stripslashes()

$result = json_encode(striptslashes(array("O\'Reiley")));
if(json_last_error() > 0){
   $result = json_encode(array("O\'Reiley"));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消