How to decode this array of object to Php array, I used json_decode() but that returned Null
$a = "[
{
id:1,
name:'rajan',
class:10
},{
id:2,
name:'amrit',
class:12
},{
id:3,
name:'arun',
class:11
}
]";
How to decode this array of object to Php array, I used json_decode() but that returned Null
$a = "[
{
id:1,
name:'rajan',
class:10
},{
id:2,
name:'amrit',
class:12
},{
id:3,
name:'arun',
class:11
}
]";
Your JSON is not valid, which is why json_decode is returning null.
SyntaxError: Unexpected token i
http://php.net/manual/en/function.json-decode.php
Returns the value encoded in json in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
I have also fixed your JSON:
[
{
"id": 1,
"name":"rajan",
"class":10
},{
"id":2,
"name":"amrit",
"class":12
},{
"id":3,
"name":"arun",
"class":11
}
]
Fixing your broken JSON with code:
$replace_keys = preg_replace("/(\w*):/i", '"$1":', $a);
$fix_values = preg_replace("/:'(\w*)'/i", ':"$1"', $replace_keys);
You can then use $replace_keys
in json_decode
. I am not sure if this is the best method, as small variations in your json could break it, but it fixes it with the example provided.
Full code to fix JSON:
$a = "[
{
id:1,
name:'rajan',
class:10
},{
id:2,
name:'amrit',
class:12
},{
id:3,
name:'arun',
class:11
}
]";
$replace_keys = preg_replace("/(\w*):/i", '"$1":', $a);
$fix_values = preg_replace("/:'(\w*)'/i", ':"$1"', $replace_keys);
die($fix_values);