Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why doesn't PHP function json_decode() work on strings formatted in double quotes?

Why does json_decode() function in php return nothing in the code below?

<?php
$str = "[['123'],['123']]";
print_r(json_decode($str));
?>

Result:
Literally white screen of death. Cause Im running this on browser.

Note!

If I change the string that is stored inside of variable $str from having double quotes, to having single quotes the json_decode() works as intended.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

E.X (pay attention to the single/double quotes from previous piece of code in comparrasion to this code below):

<?php
$str = '[["123"],["123"]]';
print_r(json_decode($str));
?>

Result:

Array ( [0] => Array ( [0] => 123 ) [1] => Array ( [0] => 123 ) )

Thanks in advance for your time and effort! The code written above is the only thing that exist in the .php file meaning that theres no more code written as part of the above script examples.

>Solution :

In the JSON syntax, strings must be enclosed into double quotes, single quotes are not valid.

json_decode() returns NULL if it failed to decode the string. You can retrieve the error message with json_last_error_msg() :

$ret = json_decode($str);
if(is_null($ret)) echo(json_last_error_msg());

Output :

Syntax error

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading