IT13122256 Ranawaka R.A.S.M IT13122256 Ranawaka R.A.S.M - 3 months ago 21
JSON Question

Json decode returns null value

i know this question ask many time before but still i could't get this working.
i have a json and when i dump

$TenentsAccessible
output is this

string(71) "[{`TenantID`:`test.com`,`Name`:`12thdoor`}]"


i need to get the value inside
TenantID
property. so i use json decode to convert this to php array but is returns
null


$jnTenant = json_decode($TenentsAccessible,TRUE);
$tenantID = $jnTenant["TenantID"];
var_dump($jnTenant); // this return null


i try to remove the
&quot
and unwanted characters using this

$TenentsAccessible = str_replace('"', '"', $TenentsAccessible);
$TenentsAccessible=preg_replace('/\s+/', '',$TenentsAccessible);


i know this type of question ask before but i still could't get this to work. appropriate the hlep. thanks

Answer

you can check your json code on JsonLint.

I tried your code and it's not correct because of backticks (`).

So you should replace with (") to have

[{
    "TenantID": "test.com",
    "Name": "12thdoor"
}]

As hasan described in his answer, json_decode returns a multi-dimensional array, so to get TenantID:

$jnTenant = json_decode('[{"TenantID":"test.com","Name":"12thdoor"}]',true);           
$tenantID = $jnTenant[0]['TenantID'];
var_dump($tenantID) ; 

If you want to get the "TenantID" in the way you described, you have to modify (if you can) the json like this

{
    "TenantID": "test.com",
    "Name": "12thdoor"
}

Hope it helps.