我使用JSON.stringify将JSON对象转换为字符串,将其存储在数据库中并检索它。当我尝试使用json_decode()将其解码为json时,它返回NULL(我使用var_dump()来验证它。)
{"profilediv":" klsadnlksa ","profilediv2":" sankldnlkas ","profilediv3":" nsjakdnsjka "}
{"profilediv":"nsjakdnsjka","profilediv2":"sankldnlkas","profilediv3":"klsadnlksa"}
我能够解析第二个字符串,但不能解析第一个字符串。这里是整个代码。
<?php
$x = '{"profilediv":"
klsadnlksa
","profilediv2":"
sankldnlkas
","profilediv3":"
nsjakdnsjka
"}';
$x = trim($x);
$y = json_decode($x,true);
var_dump($y);
$json = '{"profilediv":"nsjakdnsjka","profilediv2":"sankldnlkas","profilediv3":"klsadnlksa"}';
var_dump(json_decode($json));
?>
这是输出
NULL object(stdClass)#1 (3) { ["profilediv"]=> string(11) "nsjakdnsjka" ["profilediv2"]=> string(11) "sankldnlkas" ["profilediv3"]=> string(10) "klsadnlksa" }
我能够解析$ json而不是$ x。任何帮助表示赞赏。谢谢。
答案 0 :(得分:0)
添加此项以删除新行
$x = str_replace("\n",'',$x);
$y = json_decode($x,true);
将var_dump
编辑为:
Array
(
[profilediv] => klsadnlksa
[profilediv2] => sankldnlkas
[profilediv3] => nsjakdnsjka
)
trim - 从字符串的开头和结尾中删除空格(或其他字符)
答案 1 :(得分:0)
function json_decode_with_new_lines($json, $assoc = TRUE){
$json = str_replace("\n", "\\n", $json);
$json = str_replace("\r", "", $json);
return json_decode($json, $assoc);
}
会给出输出:
Array
(
[profilediv] =>
klsadnlksa
[profilediv2] =>
sankldnlkas
[profilediv3] =>
nsjakdnsjka
)