Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP json_decode Not Working

Tags:

json

php

Alright, so, I have a game that uploads data in the form of JSON to my site. The JSON resembles this:

{
  "PlayerList":[
    {
        "PlayerKills":0,
        "Username":"Player1",
        "TimePlayed":0,
        "Deaths":0
    },
    {
        "PlayerKills":0,
        "Username":"Player1",
        "TimePlayed":0,
        "Deaths":0
    }
  ]
}

After confirming that the JSON is indeed correct, and without errors, I began speculating that the problem lie in the PHP. The code I use to get the JSON is:

$decodedJSON =  json_decode($entityBody, true, 4);              
var_dump($decodedJSON);

With $entitybody being the JSON as a string.

The var_dump here returns NULL, and since I'm stuck using PHP 5.2, I cannot determine what the problem is using json_last_error.

So if anyone can provide me some info as to where the problem lies, it would be much appreciated.

like image 610
user3376748 Avatar asked Dec 28 '25 17:12

user3376748


2 Answers

Try this:

$entityBody = stripslashes($entityBody);
// this will remove all backslashes which might be the cause of returning NULL

$decodedJSON = json_decode($entityBody, true);
// leave out the depth unless you really need it to be 4.

var_dump($decodedJSON);

Documentation:

stripslashes - http://php.net/manual/en/function.stripslashes.php

json_decode - http://php.net/json_decode

like image 150
Akshay Kalose Avatar answered Dec 31 '25 05:12

Akshay Kalose


Don't set the depth parameter. Just json_decode($entityBody,true); should work.

like image 39
Niet the Dark Absol Avatar answered Dec 31 '25 05:12

Niet the Dark Absol