2013-11-02 54 views
0

我有以下json文件。我需要在PHP中的代碼來解析它。我嘗試了所有可能的方式,但沒有運氣。我不是json解析方面的專家。使用PHP解析此json文件

{ 
    "_id" : { "oid" : "5213785fe4b0780ba56884d3" }, 
    "author" : "Remate.ph", 
    "message" : "Suspected ASG abducts trader in Zamboanga City http://t.co/4hUttNPI", 
    "time_created" : 1357958119000, 
    "version" : "v2.1",   
}, 
{ 
    "_id" : { "oid" : "5213785fe4b0780ba56884d6" }, 
    "author" : "Clydepatrick Jayme ", 
    "message" : "RT @iFootballPlanet: 74' Osasuna 0 - 0 Real Madrid\n\n-ASG.", 
    "time_created" : 1358022721000, 
    "version" : "v2.1",    
} 

我以下面的方式修改了上面的json文件。我爲它編寫了PHP解析代碼,它工作正常。

{ 
"info1":{ 
       "_id" : { "oid" : "5213785fe4b0780ba56884d3" }, 
       "author" : "Remate.ph", 
       "message" : "Suspected ASG abducts trader in Zamboanga City http://t.co/4hUttNPI", 
       "time_created" : 1357958119000, 
       "version" : "v2.1", 

}, 
"info2":{ 
       "_id" : { "oid" : "5213785fe4b0780ba56884d6" }, 
       "author" : "Clydepatrick Jayme ", 
       "message" : "RT @iFootballPlanet: 74' Osasuna 0 - 0 Real Madrid\n\n-ASG.", 
       "time_created" : 1358022721000, 
       "version" : "v2.1", 

} 
} 

我用下面的代碼來解析它。

<?php 
//$string=file_get_contents("/Users/Anirudh/Downloads/test.json"); 
$string=file_get_contents("/Users/Anirudh/Sem-1/RA/Test/test.json"); 
$json_a=json_decode($string,true); 

$jsonIterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($json_a),RecursiveIteratorIterator::SELF_FIRST); 
//$jsonIterator = new RecursiveArrayIterator(json_decode($string, TRUE)); 
foreach ($jsonIterator as $key => $val) { 
echo "$key => $val\n"; 
} 
?> 

有人可以幫助我獲得使用PHP解析的第一個json格式嗎?

+0

你會得到什麼錯誤? –

+1

解析得到什麼? '$ json_a'中的內容數組有什麼問題? –

+0

你說你想解析它,但你已經創建了一個數組,允許你訪問內容的所有變量......定義解析。 – Popnoodles

回答

1

您的JSON文件有兩個錯誤:

  1. 兩個用逗號(INFO1和INFO2)分離第一級的項目必須是一個數組,包住整個字符串用括號[]
  2. 最後2級物品(版本) - 刪除尾隨逗號"version" : "v2.1",

修正JSON:

[{ 
    "_id" : { "oid" : "5213785fe4b0780ba56884d3" }, 
    "author" : "Remate.ph", 
    "message" : "Suspected ASG abducts trader in Zamboanga City http://t.co/4hUttNPI", 
    "time_created" : 1357958119000, 
    "version" : "v2.1" 
}, 
{ 
    "_id" : { "oid" : "5213785fe4b0780ba56884d6" }, 
    "author" : "Clydepatrick Jayme ", 
    "message" : "RT @iFootballPlanet: 74' Osasuna 0 - 0 Real Madrid\n\n-ASG.", 
    "time_created" : 1358022721000, 
    "version" : "v2.1" 
}]