如何用PHP解析JSON文件?

时间:2010-12-03 08:11:32

标签: php json

我尝试使用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循环。

我很感激这个例子。

16 个答案:

答案 0 :(得分:303)

要迭代多维数组,可以使用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

run on codepad

答案 1 :(得分:110)

我无法相信很多人在没有正确阅读JSON的情况下发布答案。

如果你预先单独迭代$json_a,你就有了一个对象对象。即使你传递true作为第二个参数,你也有一个二维数组。如果你在第一个维度上循环,你就不能像这样回应第二个维度。所以这是错误的:

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

要回应每个人的状态,请尝试以下方法:

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

?>

答案 2 :(得分:41)

最优雅的解决方案:

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

答案 3 :(得分:17)

尝试

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

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

答案 4 :(得分:16)

没有人指出你开始的“标签”是错误的,这完全超出了我。您正在使用{}创建对象,而可以使用[]创建数组。

[ // <-- 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将被解析为数组而不是对象。使用该数组,您可以执行任何操作,例如循环等。

答案 5 :(得分:15)

试试这个

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

答案 6 :(得分:9)

尝试:

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

答案 7 :(得分:9)

更标准的答案:

  <% 
  response.setContentType("application/vnd.ms-excel");
  response.setHeader("Content-disposition","attachment;filename=Data.xlsx")%>

输出是:

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

答案 8 :(得分:7)

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

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

答案 9 :(得分:3)

试一试:

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

答案 10 :(得分:3)

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

?>

答案 11 :(得分:1)

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

答案 12 :(得分:0)

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

}

答案 13 :(得分:0)

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

foreach($data as $object) {

        foreach($object as $value) {

            echo $value;

        }

    }

答案 14 :(得分:-1)

你必须这样:

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

echo "<>"

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

br inside <>

结果如下:

wait
active

答案 15 :(得分:-1)

我正在使用以下代码将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) );
?>