I used JSON.stringify to convert a JSON object to string, stored it in a database and retrieved it. When I am trying to decode it into json using json_decode(), it is returning NULL(I used var_dump() to verify it).
{"profilediv":" klsadnlksa ","profilediv2":" sankldnlkas ","profilediv3":" nsjakdnsjka "}
{"profilediv":"nsjakdnsjka","profilediv2":"sankldnlkas","profilediv3":"klsadnlksa"}
I am able to parse the second string, but not the first one. Here the entire code.
<?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));
?>
And here is the output
NULL object(stdClass)#1 (3) { ["profilediv"]=> string(11) "nsjakdnsjka" ["profilediv2"]=> string(11) "sankldnlkas" ["profilediv3"]=> string(10) "klsadnlksa" }
I am able to parse $json but not $x. Any help is appreciated.Thanks in advance.
Add this to remove new-lines
$x = str_replace("
",'',$x);
$y = json_decode($x,true);
Will be var_dump
ed as:
Array
(
[profilediv] => klsadnlksa
[profilediv2] => sankldnlkas
[profilediv3] => nsjakdnsjka
)
trim — Strip whitespace (or other characters) from the beginning and end of a string
function json_decode_with_new_lines($json, $assoc = TRUE){
$json = str_replace("
", "\
", $json);
$json = str_replace("", "", $json);
return json_decode($json, $assoc);
}
Will give output:
Array
(
[profilediv] =>
klsadnlksa
[profilediv2] =>
sankldnlkas
[profilediv3] =>
nsjakdnsjka
)