PHP的json_decode()与此JSON字符串

时间:2011-09-15 12:08:16

标签: php arrays json jsonlint

我有这个JSON字符串:

 {
    "name": "test task1",
    "desc": "test desc1",
    "id": "1"
}{
    "name": "test task1aaaa",
    "desc": "test desc1",
    "id": "2"
}

但它看起来不正确(JSONLint告诉我)因此PHP的json_decode()无法对其进行解码。有什么方法可以将两个JSON数组分成两个字符串(或数组的字符串数),以便json_decode解码它们?

3 个答案:

答案 0 :(得分:2)

假设您的目的是拥有两个元素的数组,那么您的JSON应该如下所示:

[
    {
        "name": "test task1",
        "desc": "test desc1",
        "id": "1"
    },{
        "name": "test task1aaaa",
        "desc": "test desc1",
        "id": "2"
    }
]

答案 1 :(得分:0)

最直接的

$str = ' {
    "name": "test task1",
    "desc": "test desc1",
    "id": "1"
}{
    "name": "test task1aaaa",
    "desc": "test desc1",
    "id": "2"
}';

var_dump(json_decode('['.str_replace('}{','},{',$str).']'));

答案 2 :(得分:0)

<?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));