这旨在作为一般参考问题,涵盖许多永无止境的"如何访问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不是数组,对象或数据结构。 JSON 是一种基于文本的序列化格式,因此是花哨的字符串,但仍然只是字符串。通过使用 json_decode()
在PHP中对其进行解码。
$data = json_decode($json);
您可能会发现:
这些都是可以用JSON编码的东西。更准确地说,这些是PHP的版本,可以用JSON编码。
它们没有什么特别的。它们不是" JSON对象"或" JSON数组"。您已经解码了JSON-现在您有了基本的日常PHP类型。
对象将是 stdClass 的实例,该内置类是只是一般的东西,在这里并不重要。
您可以通过相同的方式访问其中一个对象的属性您可以使用任何其他对象的公共非静态属性,例如$object->属性
。
$json = '
{
"type": "donut",
"name": "Cake"
}';
$yummy = json_decode($json);
echo $yummy->type; //donut
您可以像访问任何其他数组一样的方式访问这些数组之一的元素,例如 $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";
}
上釉的
洒巧克力
枫木
或者与任何庞大的内置数组函数混在一起。
访问嵌套项目
对象的属性和数组的元素可能是更多的对象和/或数组-您可以像往常一样继续访问它们的属性和成员,例如$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()
执行此操作时,您将获得关联数组-带有键字符串的数组,而不是对象。同样,您可以像往常一样访问其元素。 $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 对象解码为关联的PHP数组时,可以使用 foreach(array_expression为$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-在哪里看到大括号{}
需要一个对象,在哪里看到方括号[]
需要一个数组。
使用 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);
并检查输出:
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
)
)
)
它将告诉您在哪里有对象,在哪里有数组以及它们的成员的名称和值。
如果您只能迷迷糊糊地走那么远,请走远然后用print_r()
击中那个:
print_r($yummy->toppings[0]);
stdClass Object
(
[id] => 5002
[type] => Glazed
)
在这个方便的交互式JSON资源管理器中进行查看。
将问题分解为更容易解决的问题。
json_decode()
返回null
发生这种情况的原因是:
- JSON完全由
null
组成。
- JSON无效-检查
的结果json_last_error_msg
或通过类似 JSONLint 的方式放置。
- 它包含嵌套超过512级的元素。通过将整数作为第三个参数传递给
json_decode()
,可以覆盖此默认最大深度>。
如果您需要更改最大深度,则可能是在解决错误的问题。找出为什么要获取如此深层的嵌套数据(例如,正在查询的生成JSON的服务存在错误),并使其无法实现。
对象属性名称包含特殊字符
有时,您将拥有一个对象属性名称,其中包含连字符-
或符号@
之类的内容,不能在文字标识符中使用。相反,您可以在花括号中使用字符串文字来解决它。
$json = '{"@attributes":{"answer":42}}';
$thing = json_decode($json);
echo $thing->{'@attributes'}->answer; //42
如果您使用整数作为属性,请参见:如何以类似整数的名称访问对象属性?。
有人将JSON放入您的JSON
这很荒谬,但它确实发生了-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()将json字符串转换为PHP对象/数组。
例如。
输入:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
输出:
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
需要记住的几点:
json_decode
要求字符串为有效的json
,否则将返回NULL
。json_last_error()
可用于确定错误的确切性质。utf8
内容,否则json_decode
可能会出错,并仅返回NULL
值。// 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
上面的答案很快就消失了,我想更进一步,从JSON中获取单个变量。我的解决办法是...
$my_json = '{"cat": "Tibbles", "dog": "Rover", "rabbit": "Flopsy"}';
extract(json_decode($my_json, true));
echo "Dog: $dog; Rabbit: $rabbit; Cat: $cat";
注意:请勿在不受信任的数据上使用,因为 extract()允许覆盖局部变量。 (我的应用程序是一个独立的分析,正在导入和导出自己的数据)。
考虑使用JSONPath
https://packagist.org/packages/flow / jsonpath
关于如何使用它并解析JSON文件避免提出的所有循环,有一个非常清晰的解释。如果您熟悉XML
的XPath
,您将开始喜欢这种方法。
我已经写了一个名为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
检查以下代码,以将PHP
中的json转换为数组,如果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) );
您可以根据需要使用任何功能,