如何将这个对象数组解码为Php数组,我使用了json_decode()但返回了Null
$a = "[
{
id:1,
name:'rajan',
class:10
},{
id:2,
name:'amrit',
class:12
},{
id:3,
name:'arun',
class:11
}
]";
Run Code Online (Sandbox Code Playgroud)
您的JSON无效,这就是json_decode返回null的原因.
SyntaxError: Unexpected token i
http://php.net/manual/en/function.json-decode.php
以适当的PHP类型返回json中编码的值.值true,false和null分别返回为TRUE,FALSE和NULL.如果无法解码json或编码数据深于递归限制,则返回NULL.
我还修复了你的JSON:
[
{
"id": 1,
"name":"rajan",
"class":10
},{
"id":2,
"name":"amrit",
"class":12
},{
"id":3,
"name":"arun",
"class":11
}
]
Run Code Online (Sandbox Code Playgroud)
使用代码修复损坏的JSON:
$replace_keys = preg_replace("/(\w*):/i", '"$1":', $a);
$fix_values = preg_replace("/:'(\w*)'/i", ':"$1"', $replace_keys);
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用$replace_keys在json_decode.我不确定这是否是最好的方法,因为你的json中的小变化可能会破坏它,但它会用提供的示例修复它.
修复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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
73 次 |
| 最近记录: |