[英]How to extract and access data from JSON with PHP?
这是一个通用的参考问答,涵盖许多永无止境的“我如何访问我的 JSON 中的数据?” 问题。 它在这里处理在 PHP 中解码 JSON 和访问结果的广泛基础。
我有 JSON:
{
"type": "donut",
"name": "Cake",
"toppings": [
{ "id": "5002", "type": "Glazed" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5004", "type": "Maple" }
]
}
如何在 PHP 中对此进行解码并访问结果数据?
首先你有一个字符串。 JSON 不是数组、object 或数据结构。 JSON是一种基于文本的序列化格式 - 所以是一个花哨的字符串,但仍然只是一个字符串。 使用json_decode()
在 PHP 中对其进行解码。
$data = json_decode($json);
其中你可能会发现:
这些是可以在 JSON 中编码的东西。 或者更准确地说,这些是可以在 JSON 中编码的东西的 PHP 版本。
他们没有什么特别的。 它们不是“JSON 对象”或“JSON arrays”。 您已经解码了 JSON - 您现在拥有基本的日常 PHP 类型。
对象将是stdClass的实例,一个内置的 class 只是一个通用的东西,在这里并不重要。
您可以像访问任何其他 object 的公共非静态属性(例如$object->property
)一样访问这些对象之一的属性。
$json = '
{
"type": "donut",
"name": "Cake"
}';
$yummy = json_decode($json);
echo $yummy->type; //donut
您可以访问这些 arrays 之一的元素,就像访问任何其他数组一样,例如$array[0]
。
$json = '
[
"Glazed",
"Chocolate with Sprinkles",
"Maple"
]';
$toppings = json_decode($json);
echo $toppings[1]; //Chocolate with Sprinkles
使用foreach
对其进行迭代。
foreach ($toppings as $topping) {
echo $topping, "\n";
}
釉面
巧克力洒
枫
或者搞乱任何大量的内置数组函数。
对象的属性和 arrays 的元素可能是更多对象和/或 arrays - 您可以像往常一样简单地继续访问它们的属性和成员,例如$object->array[0]->etc
。
$json = '
{
"type": "donut",
"name": "Cake",
"toppings": [
{ "id": "5002", "type": "Glazed" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5004", "type": "Maple" }
]
}';
$yummy = json_decode($json);
echo $yummy->toppings[2]->id; //5004
true
作为第二个参数传递给json_decode() 当您执行此操作时,您将获得关联的 arrays - arrays 与键的字符串,而不是对象。 再次像往常一样访问其中的元素,例如$array['key']
。
$json = '
{
"type": "donut",
"name": "Cake",
"toppings": [
{ "id": "5002", "type": "Glazed" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5004", "type": "Maple" }
]
}';
$yummy = json_decode($json, true);
echo $yummy['toppings'][2]['type']; //Maple
将 JSON object解码为关联的 PHP 数组时,您可以使用foreach (array_expression as $key => $value)
迭代键和值
$json = '
{
"foo": "foo value",
"bar": "bar value",
"baz": "baz value"
}';
$assoc = json_decode($json, true);
foreach ($assoc as $key => $value) {
echo "The value of key '$key' is '$value'", PHP_EOL;
}
印刷
键'foo'的值是'foo value'
键'bar'的值是'bar value'
键'baz'的值是'baz value'
阅读文档以了解您从中获得 JSON 的任何内容。
查看 JSON - 您看到大括号{}
期望 object,您看到方括号[]
期望数组。
用print_r()
击中解码的数据:
$json = '
{
"type": "donut",
"name": "Cake",
"toppings": [
{ "id": "5002", "type": "Glazed" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5004", "type": "Maple" }
]
}';
$yummy = json_decode($json);
print_r($yummy);
并检查 output:
stdClass Object
(
[type] => donut
[name] => Cake
[toppings] => Array
(
[0] => stdClass Object
(
[id] => 5002
[type] => Glazed
)
[1] => stdClass Object
(
[id] => 5006
[type] => Chocolate with Sprinkles
)
[2] => stdClass Object
(
[id] => 5004
[type] => Maple
)
)
)
它会告诉您在哪里有对象,在哪里有 arrays,以及它们的成员的名称和值。
如果您在迷路之前只能深入了解它 - go 并用print_r()
击中它:
print_r($yummy->toppings[0]);
stdClass Object
(
[id] => 5002
[type] => Glazed
)
在这个方便的交互式 JSON explorer中查看它。
将问题分解成更容易理解的部分。
json_decode()
返回null
发生这种情况是因为:
null
组成。json_last_error_msg
的结果或通过JSONLint之类的方法。json_decode()
来覆盖。如果您需要更改最大深度,您可能正在解决错误的问题。 找出为什么你会得到如此深的嵌套数据(例如,你正在查询的生成 JSON 的服务有一个错误)并让它不会发生。
有时您会拥有一个 object 属性名称,其中包含类似连字符的内容-
或符号@
不能在文字标识符中使用。 相反,您可以在花括号内使用字符串文字来解决它。
$json = '{"@attributes":{"answer":42}}';
$thing = json_decode($json);
echo $thing->{'@attributes'}->answer; //42
如果您有一个 integer 作为属性,请参阅: 如何访问 object 属性名称如整数? 作为参考。
这很荒谬,但它确实发生了 - 在 JSON 中有 JSON 编码为字符串。 解码,像往常一样访问字符串,解码,最终得到你需要的。
$json = '
{
"type": "donut",
"name": "Cake",
"toppings": "[{ \"type\": \"Glazed\" }, { \"type\": \"Maple\" }]"
}';
$yummy = json_decode($json);
$toppings = json_decode($yummy->toppings);
echo $toppings[0]->type; //Glazed
如果您的 JSON 太大而json_decode()
无法立即处理,事情就开始变得棘手。 看:
您可以使用json_decode()<\/a>将 json 字符串转换为 PHP 对象\/数组。
例如。
输入:<\/strong>
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
// Using json as php array
$json = '[{"user_id":"1","user_name":"Sayeed Amin","time":"2019-11-06 13:21:26"}]';
//or use from file
//$json = file_get_contents('results.json');
$someArray = json_decode($json, true);
foreach ($someArray as $key => $value) {
echo $value["user_id"] . ", " . $value["user_name"] . ", " . $value["time"] . "<br>";
}
我们可以使用 php 中的 json_decode 函数将 json 字符串解码为数组
1) json_decode($json_string) // 它返回对象
2) json_decode($json_string,true) // 它返回数组
$json_string = '{
"type": "donut",
"name": "Cake",
"toppings": [
{ "id": "5002", "type": "Glazed" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5004", "type": "Maple" }
]
}';
$array = json_decode($json_string,true);
echo $array['type']; //it gives donut
考虑使用
JSONPath<\/code>
https:\/\/packagist.org\/packages\/flow\/jsonpath<\/a>
关于如何使用它并解析 JSON 文件避免了所有建议的循环<\/strong>,有一个非常清楚的解释。 如果您熟悉
XPath<\/code> for
XML<\/code> ,您将开始喜欢这种方法。
在大多数情况下,接受的答案非常详细和正确。
我只想补充一点,我在尝试加载使用 UTF8 编码的 JSON 文本文件时遇到错误,我有一个格式正确的 JSON,但 'json_decode' 总是返回 NULL,这是由于BOM 标记。
为了解决这个问题,我做了这个 PHP 函数:
function load_utf8_file($filePath)
{
$response = null;
try
{
if (file_exists($filePath)) {
$text = file_get_contents($filePath);
$response = preg_replace("/^\xEF\xBB\xBF/", '', $text);
}
} catch (Exception $e) {
echo 'ERROR: ', $e->getMessage(), "\n";
}
finally{ }
return $response;
}
然后我像这样使用它来加载一个 JSON 文件并从中获取一个值:
$str = load_utf8_file('appconfig.json');
$json = json_decode($str, true);
//print_r($json);
echo $json['prod']['deploy']['hostname'];
我编写了一个名为JSON
的包( GitHub , Packagist )。 如果要防止使用json_*
函数的开销,则应该尝试一下。
use MAChitgarha\Component\JSON;
$jsonStr = <<<JSON
{
"type": "donut",
"name": "Cake",
"toppings": [
{ "id": "5002", "type": "Glazed" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5004", "type": "Maple" }
]
}
JSON;
// Create an instance
$json = new JSON($jsonStr);
// Get a nested element using dots
$json->get("toppings.1.type"); // Chocolate with Sprinkles
$json["toppings.1.type"]; // Chocolate with Sprinkles
// Iterate over an element
foreach ($json->iterate("toppings") as $item)
echo "{$item->id}: {$item->type}", PHP_EOL;
// Change an element
$json->set("toppings.3", [
"id" => "5000",
"type" => "Unknown"
]);
// Get data as JSON string, array or object, respectively
$json->getDataAsJson();
$json->getDataAsArray();
$json->getDataAsObject();
此外,如果您想读取JSON文件并提取其数据(似乎您正在尝试执行此操作),请参阅JSONFile包,我也已经编写了它。
https:\/\/paiza.io\/projects\/X1QjjBkA8mDo6oVh-J_63w<\/a>
检查以下代码在
PHP<\/code>中将 json 转换为数组,如果 JSON 正确,则
json_decode()<\/code>运行良好,并将返回一个数组,但如果 JSON 格式错误,则它将返回
NULL<\/code> ,
<?php
function jsonDecode1($json){
$arr = json_decode($json, true);
return $arr;
}
// In case of malformed JSON, it will return NULL
var_dump( jsonDecode1($json) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.