【问题标题】:PHP's json_decode() with this JSON string带有此 JSON 字符串的 PHP json_decode()
【发布时间】:2011-09-15 12:08:16
【问题描述】:
我有这个 JSON 字符串:
{
"name": "test task1",
"desc": "test desc1",
"id": "1"
}{
"name": "test task1aaaa",
"desc": "test desc1",
"id": "2"
}
但它看起来不正确(JSONLint 告诉我)所以 PHP 的 json_decode() 无法解码它。有什么方法可以将两个 JSON 数组分成两个字符串(或数组是多少字符串)以使json_decode 对其进行解码?
【问题讨论】:
标签:
php
arrays
json
jsonlint
【解决方案1】:
假设您的意图是拥有一个包含两个元素的数组,您的 JSON 应该如下所示:
[
{
"name": "test task1",
"desc": "test desc1",
"id": "1"
},{
"name": "test task1aaaa",
"desc": "test desc1",
"id": "2"
}
]
【解决方案2】:
最直接的
$str = ' {
"name": "test task1",
"desc": "test desc1",
"id": "1"
}{
"name": "test task1aaaa",
"desc": "test desc1",
"id": "2"
}';
var_dump(json_decode('['.str_replace('}{','},{',$str).']'));
【解决方案3】:
<?php
$str='{
"name": "test task1",
"desc": "test desc1",
"id": "1"
}{
"name": "test task1aaaa",
"desc": "test desc1",
"id": "2"
}';
$arrays = explode("{", $str);
foreach($arrays as &$arr) $arr='{'.$arr;
//decode
foreach ($arrays as $arr) print_r(json_decode($arr,true));