Home > Back-end >  Why doesn't PHP function json_decode() work on strings formatted in double quotes?
Why doesn't PHP function json_decode() work on strings formatted in double quotes?

Time:01-09

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.

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.

CodePudding user response:

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

  • Related