¿Cómo puedo analizar un archivo JSON con PHP?


Traté de analizar un archivo JSON usando PHP. Pero ahora estoy atascado.

Este es el contenido de mi archivo JSON:

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

Y esto es lo que he intentado hasta ahora:

<?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];

Pero porque no conozco los nombres (como 'John', 'Jennifer') y todas las claves y valores disponibles (como 'age', 'count') de antemano, creo que necesito crear un bucle foreach.

Agradecería un ejemplo de esto.

 322
Author: localheinz, 2010-12-03

15 answers

Para iterar sobre una matriz multidimensional, puede usar 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";
    }
}

Salida:

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

Ejecutar en codepad

 287
Author: Gordon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-27 12:58:43

No puedo creer que tanta gente esté publicando respuestas sin leer el JSON correctamente.

Si usted foreach itera $json_a solo, usted tiene un objeto de objetos. Incluso si pasa true como segundo parámetro, tiene una matriz bidimensional. Si estás en bucle a través de la primera dimensión no puedes hacer eco de la segunda dimensión así. Así que esto está mal:

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

Para hacer eco de los estados de cada persona, prueba esto:

<?php

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

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

?>
 93
Author: BoltClock,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-03 08:22:42

La solución más elegante:

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

Recuerde que el archivo json debe estar codificado en UTF-8 sin BOM. Si el archivo tiene BOM, entonces json_decode devolverá NULL.

Alternativamente:

$shipments = json_encode(json_decode(file_get_contents("shipments.js"), true));
echo $shipments;
 33
Author: swift,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-17 13:35:59

Intenta

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

foreach ($json_a as $key => $value){
  echo  $key . ':' . $value;
}
?>
 16
Author: Thariama,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-03 08:17:37

Es completamente más allá de mí que nadie señaló que sus "etiquetas" iniciales están equivocadas. Estás creando un objeto con {}, mientras que podrías crear un array con [].

[ // <-- 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.

Con este cambio, el json se analizará como una matriz en lugar de un objeto. Y con esa matriz, puedes hacer lo que quieras, como bucles, etc.

 13
Author: David,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-21 13:07:00

Prueba esto

$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);
}
 10
Author: vivek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-05 22:00:40

Intenta:

$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 />';
        }
    }
}
 9
Author: Indrajeet Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-31 04:21:39

Recorre el JSON con un bucle foreach como pares clave-valor. Haga una comprobación de tipo para determinar si es necesario realizar más bucles.

foreach($json_a as $key => $value) {
    echo $key;
    if (gettype($value) == "object") {
        foreach ($value as $key => $value) {
          # and so on
        }
    }
}
 7
Author: Alex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-03 08:19:02

Respuesta más estándar:

$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;

Y la salida es:

Name: John
 Status = Wait
Name: Jennifer
 Status = Active
Name: James
 Status = Active
 Age = 56
 Count = 10
 Progress = 0.0029857
 Bad = 0
 7
Author: Priyabrata Atha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-03 07:53:06

Pruébalo:

foreach ($json_a as $key => $value)
 {
   echo $key, ' : ';
   foreach($value as $v)
   {
       echo $v."  ";
   }
}
 3
Author: Hamender,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-31 12:22:21

Cuando decodifica una cadena json, obtendrá un objeto. no una matriz. Así que la mejor manera de ver la estructura que está recibiendo, es hacer un var_dump de la decodificación. (este var_dump puede ayudarle a entender la estructura, principalmente en casos complejos).

<?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";
     }
?>
 1
Author: Daniel Blanco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-25 01:08:42
<?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']; 

?>
 1
Author: sunny bhadania,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-03 10:10:01

Tienes que dar así:

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

echo "<>"

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

br inside <>

Que da el resultado :

wait
active
 0
Author: muneeb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-26 16:38:21
$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>";
    }

}
 0
Author: user3917016,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-19 04:59:07

La forma más rápida de hacer eco de todos los valores json es usar loop in loop, el primer bucle va a obtener todos los objetos y el segundo los valores...

foreach($data as $object) {

        foreach($object as $value) {

            echo $value;

        }

    }
 0
Author: The Bumpaster,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-29 09:18:03