Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse a JSON file with PHP? [duplicate]

Tags:

json

php

I tried to parse a JSON file using PHP. But I am stuck now.

This is the content of my JSON file:

{
    "John": {
        "status":"Wait"
    },
    "Jennifer": {
        "status":"Active"
    },
    "James": {
        "status":"Active",
        "age":56,
        "count":10,
        "progress":0.0029857,
        "bad":0
    }
}

And this is what I have tried so far:

<?php

$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string, true);

echo $json_a['John'][status];
echo $json_a['Jennifer'][status];

But because I don't know the names (like 'John', 'Jennifer') and all available keys and values (like 'age', 'count') beforehand, I think I need to create some foreach loop.

I would appreciate an example for this.

like image 849
John Doe Avatar asked Dec 03 '10 08:12

John Doe


People also ask

How do I parse a JSON file?

Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

What is JSON parse () method?

parse() The JSON. parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

What is the use of json_decode in PHP?

The json_decode() function is used to decode or convert a JSON object to a PHP object.


13 Answers

To iterate over a multidimensional array, you can use RecursiveArrayIterator

$jsonIterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);

foreach ($jsonIterator as $key => $val) {
    if(is_array($val)) {
        echo "$key:\n";
    } else {
        echo "$key => $val\n";
    }
}

Output:

John:
status => Wait
Jennifer:
status => Active
James:
status => Active
age => 56
count => 10
progress => 0.0029857
bad => 0

run on codepad

like image 57
Gordon Avatar answered Oct 03 '22 17:10

Gordon


I can't believe so many people are posting answers without reading the JSON properly.

If you foreach iterate $json_a alone, you have an object of objects. Even if you pass in true as the second parameter, you have a two-dimensional array. If you're looping through the first dimension you can't just echo the second dimension like that. So this is wrong:

foreach ($json_a as $k => $v) {
   echo $k, ' : ', $v;
}

To echo the statuses of each person, try this:

<?php

$string = file_get_contents("/home/michael/test.json");
if ($string === false) {
    // deal with error...
}

$json_a = json_decode($string, true);
if ($json_a === null) {
    // deal with error...
}

foreach ($json_a as $person_name => $person_a) {
    echo $person_a['status'];
}

?>
like image 44
BoltClock Avatar answered Oct 03 '22 17:10

BoltClock


The most elegant solution:

$shipments = json_decode(file_get_contents("shipments.js"), true);
print_r($shipments);

Remember that the json-file has to be encoded in UTF-8 without BOM. If the file has BOM, then json_decode will return NULL.

Alternatively:

$shipments = json_encode(json_decode(file_get_contents("shipments.js"), true));
echo $shipments;
like image 45
swift Avatar answered Oct 05 '22 17:10

swift


Try

<?php
$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string,true);

foreach ($json_a as $key => $value){
  echo  $key . ':' . $value;
}
?>
like image 34
Thariama Avatar answered Oct 04 '22 17:10

Thariama


It's completely beyond me that no one pointed out that your begining "tags" are wrong. You're creating an object with {}, while you could create an array with [].

[ // <-- Note that I changed this
    {
        "name" : "john", // And moved the name here.
        "status":"Wait"
    },
    {
        "name" : "Jennifer",
        "status":"Active"
    },
    {
        "name" : "James",
        "status":"Active",
        "age":56,
        "count":10,
        "progress":0.0029857,
        "bad":0
    }
] // <-- And this.

With this change, the json will be parsed as an array instead of an object. And with that array, you can do whatever you want, like loops etc.

like image 27
David Avatar answered Oct 03 '22 17:10

David


Try This

    $json_data = '{
    "John": {
        "status":"Wait"
    },
    "Jennifer": {
        "status":"Active"
    },
    "James": {
        "status":"Active",
        "age":56,
        "count":10,
        "progress":0.0029857,
        "bad":0
      }
     }';

    $decode_data = json_decode($json_data);
    foreach($decode_data as $key=>$value){

            print_r($value);
    }
like image 42
vivek Avatar answered Oct 05 '22 17:10

vivek


Try:

$string = file_get_contents("/home/michael/test.json");
$json = json_decode($string, true);

foreach ($json as $key => $value) {
    if (!is_array($value)) {
        echo $key . '=>' . $value . '<br />';
    } else {
        foreach ($value as $key => $val) {
            echo $key . '=>' . $val . '<br />';
        }
    }
}
like image 39
Indrajeet Singh Avatar answered Oct 04 '22 17:10

Indrajeet Singh


More standard answer:

$jsondata = file_get_contents(PATH_TO_JSON_FILE."/jsonfile.json");

$array = json_decode($jsondata,true);

foreach($array as $k=>$val):
    echo '<b>Name: '.$k.'</b></br>';
    $keys = array_keys($val);
    foreach($keys as $key):
        echo '&nbsp;'.ucfirst($key).' = '.$val[$key].'</br>';
    endforeach;
endforeach;

And the output is:

Name: John
 Status = Wait
Name: Jennifer
 Status = Active
Name: James
 Status = Active
 Age = 56
 Count = 10
 Progress = 0.0029857
 Bad = 0
like image 34
Diptesh Atha Avatar answered Oct 01 '22 17:10

Diptesh Atha


Loop through the JSON with a foreach loop as key-value pairs. Do type-checking to determine if more looping needs to be done.

foreach($json_a as $key => $value) {
    echo $key;
    if (gettype($value) == "object") {
        foreach ($value as $key => $value) {
          # and so on
        }
    }
}
like image 40
Alex Avatar answered Oct 05 '22 17:10

Alex


<?php
$json = '{
    "response": {
        "data": [{"identifier": "Be Soft Drinker, Inc.", "entityName": "BusinessPartner"}],
        "status": 0,
        "totalRows": 83,
        "startRow": 0,
        "endRow": 82
    }
}';
$json = json_decode($json, true);
//echo '<pre>'; print_r($json); exit;
echo $json['response']['data'][0]['identifier'];
$json['response']['data'][0]['entityName']
echo $json['response']['status']; 
echo $json['response']['totalRows']; 
echo $json['response']['startRow']; 
echo $json['response']['endRow']; 

?>
like image 38
sunny bhadania Avatar answered Oct 03 '22 17:10

sunny bhadania


Try it:

foreach ($json_a as $key => $value)
 {
   echo $key, ' : ';
   foreach($value as $v)
   {
       echo $v."  ";
   }
}
like image 31
Hamender Avatar answered Oct 03 '22 17:10

Hamender


When you decode a json string, you will get an object. not an array. So the best way to see the structure you are getting, is to make a var_dump of the decode. (this var_dump can help you understand the structure, mainly in complex cases).

<?php
     $json = file_get_contents('/home/michael/test.json');
     $json_a = json_decode($json);
     var_dump($json_a); // just to see the structure. It will help you for future cases
     echo "\n";
     foreach($json_a as $row){
         echo $row->status;
         echo "\n";
     }
?>
like image 35
Daniel Blanco Avatar answered Oct 01 '22 17:10

Daniel Blanco


$json_a = json_decode($string, TRUE);
$json_o = json_decode($string);



foreach($json_a as $person => $value)
{
    foreach($value as $key => $personal)
    {
        echo $person. " with ".$key . " is ".$personal;
        echo "<br>";
    }

}
like image 38
Sreejith Nhaloor Avatar answered Oct 02 '22 17:10

Sreejith Nhaloor