我尝试使用PHP解析JSON文件。但我现在被困住了。

这是我JSON文件的内容:

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

这是我目前为止所做的尝试:

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

但是因为我事先不知道名字(如“John”,“Jennifer”)和所有可用的键和值(如“age”,“count”),我认为我需要创建一些foreach循环。

我希望你能举个例子。


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

使用foreach循环作为键-值对遍历JSON。进行类型检查,以确定是否需要执行更多循环。

foreach($json_a as $key => $value) {
    echo $key;
    if (gettype($value) == "object") {
        foreach ($value as $key => $value) {
          # and so on
        }
    }
}

我不敢相信这么多人在没有正确阅读JSON的情况下就发布了答案。

如果单独迭代$json_a,就得到了一个对象的对象。即使你传入了true作为第二个参数,你也得到了一个二维数组。如果你循环遍历第一个维度你不能像这样回显第二个维度。所以这是错误的:

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

为了反映每个人的状态,试试这个:

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

?>

要遍历多维数组,可以使用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";
    }
}

输出:

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

在代码板上运行


你必须这样给予:

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

echo "<>"

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

br inside <>

结果是:

wait
active

试一试:

foreach ($json_a as $key => $value)
 {
   echo $key, ' : ';
   foreach($value as $v)
   {
       echo $v."  ";
   }
}

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 />';
        }
    }
}

当你解码一个json字符串时,你会得到一个对象。不是数组。因此,查看所获得的结构的最佳方法是对解码进行var_dump。(这个var_dump可以帮助您理解结构,主要是在复杂的情况下)。

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

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

}

最优雅的解决方案:

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

请记住,json文件必须使用UTF-8编码,不包含BOM。如果文件有BOM,那么json_decode将返回NULL。

另外:

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

我完全无法理解,居然没有人指出你开头的“标签”是错的。你可以用{}创建一个对象,而你可以用[]创建一个数组。

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

有了这个更改,json将被解析为数组而不是对象。有了这个数组,你可以做任何你想做的事情,比如循环等等。


回显所有json值的最快方法是使用循环回显,第一个循环将获得所有对象,第二个循环将获得值…

foreach($data as $object) {

        foreach($object as $value) {

            echo $value;

        }

    }

更标准的回答:

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

输出为:

Name: John
 Status = Wait
Name: Jennifer
 Status = Active
Name: James
 Status = Active
 Age = 56
 Count = 10
 Progress = 0.0029857
 Bad = 0

试试这个

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

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

?>

我使用下面的代码转换json到PHP数组, 如果JSON有效,那么json_decode()工作良好,并将返回一个数组, 但如果JSON格式不正确,它将返回NULL,

<?php
function jsonDecode1($json){
    $arr = json_decode($json, true);
    return $arr;
}

// In case of malformed JSON, it will return NULL
var_dump( jsonDecode1($json) );
?>

如果在JSON格式不正确的情况下,你只期望数组,那么你可以使用这个函数,

<?php
function jsonDecode2($json){
    $arr = (array) json_decode($json, true);
    return $arr;
}

// In case of malformed JSON, it will return an empty array()
var_dump( jsonDecode2($json) );
?>

如果JSON格式不正确,你想要停止代码执行,那么你可以使用这个函数,

<?php
function jsonDecode3($json){
    $arr = (array) json_decode($json, true);

    if(empty(json_last_error())){
        return $arr;
    }
    else{
        throw new ErrorException( json_last_error_msg() );
    }
}

// In case of malformed JSON, Fatal error will be generated
var_dump( jsonDecode3($json) );
?>