2011-09-15 75 views
2

我有這樣的JSON字符串:PHP的json_decode()與此JSON字符串

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

但它看起來像它的不正確(JSONLint告訴我),所以PHP的json_decode()無法對其進行解碼。有什麼辦法可以將兩個JSON數組分成兩個字符串(或者是多少個字符串)來使json_decode解碼它們?

回答

2

假設你的意圖有兩個元素的數組,你的JSON應該是這樣的:

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

一個不錯的JSON-驗證,以避免之類的東西這:http://jsonlint.com/ –

+0

謝謝,只是使其正確,是生成陣列錯誤:D – pmerino

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).']')); 
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));