如何使用 PHP 解析 JSON 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4343596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:44:04  来源:igfitidea点击:

How can I parse a JSON file with PHP?

phpjson

提问by John Doe

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

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

This is the content of my JSON file:

这是我的 JSON 文件的内容:

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

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

I would appreciate an example for this.

我会很感激这个例子。

采纳答案by Gordon

To iterate over a multidimensional array, you can use RecursiveArrayIterator

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

在键盘上运行

回答by BoltClock

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

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

If you foreach iterate $json_aalone, you have an object of objects. Even if you pass in trueas 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:

如果您$json_a单独进行foreach 迭代,您将拥有一个对象的对象。即使你true作为第二个参数传入,你也有一个二维数组。如果你在第一维中循环,你不能像那样回声第二维。所以这是错误的:

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

?>

回答by swift

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.

请记住,json 文件必须以没有 BOM 的 UTF-8 编码。如果文件有 BOM,则 json_decode 将返回 NULL。

Alternatively:

或者:

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

回答by Thariama

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

回答by David

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.

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

回答by vivek

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

回答by Priyabrata Atha

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

回答by Indrajeet Singh

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

回答by Alex

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

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

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

回答by sunny bhadania

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

?>