2013-11-02 53 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" 
}]