Anirudh Kashyap
Anirudh Kashyap

Reputation: 317

Parsing this json file using PHP

I have the following json file. I need code in php to parse it. I tried all possible ways but no luck. I am not an expert in json parsing.

{
     "_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",               
}

I modified the above json file in the following way. And I wrote the php parsing code for it and it works fine.

{
"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",

}
}

I used the following code to parse it.

<?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";
}
?>

Can someone help me in getting the first json format parsed using PHP ?

Upvotes: 0

Views: 99

Answers (1)

clover
clover

Reputation: 5170

Your json file has two errors:

  1. Two 1st level items separated by comma (info1 and info2) must be an array, wrap the whole string with brackets [ and ].
  2. Last 2nd level items (version) - remove trailing commas "version" : "v2.1",.

Corrected 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"
}]

Upvotes: 1

Related Questions