php - 如何使用 PHP 从 JSON 中提取数据?

This is intended to be a general reference question and answer covering many of the never-ending "How do I access data in my JSON?" questions. It is here to handle the broad basics of decoding JSON in PHP and accessing the results.



我有 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);

您可能会在其中找到:
  • 标量:strings , ints , floats , 和 bools
  • nulls (自己的特殊类型)
  • 化合物类型:objects和 arrays .

  • 这些是可以用 JSON 编码的东西。或者更准确地说,这些是可以用 JSON 编码的东西的 PHP 版本。

    他们没有什么特别之处。它们不是“JSON 对象”或“JSON 数组”。您已经解码了 JSON - 现在您拥有 basic everyday PHP types .

    对象将是 stdClass 的实例,一个内置类,它只是一个 generic thing这在这里并不重要。

    访问对象属性

    您访问 properties这些对象之一的方式与您对任何其他对象的公共(public)非静态属性相同,例如$object->property .
    $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";
    }
    

    Glazed
    Chocolate with Sprinkles
    Maple



    或者搞乱任何 bazillion built-in array functions .

    访问嵌套项

    对象的属性和数组的元素可能是更多的对象和/或数组 - 您可以像往常一样简单地继续访问它们的属性和成员,例如$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 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;
    }
    

    打印

    The value of key 'foo' is 'foo value'
    The value of key 'bar' is 'bar value'
    The value of key 'baz' is '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
    )
    

    看看在this handy interactive JSON explorer .

    将问题分解成更容易解决问题的部分。
    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
    

    如果您有一个整数作为属性,请参阅:How to access object properties with names like integers?作为引用。

    有人把 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() 来说太大了立即处理事情开始变得棘手。看:
  • Processing large JSON files in PHP
  • How to properly iterate through a big json file


  • 如何排序

    见:Reference: all basic ways to sort arrays and data in PHP .

    https://stackoverflow.com/questions/29308898/

    相关文章:

    ruby - 'json' 原生 gem 需要安装构建工具

    jquery - 如何在没有表单的情况下将字符串数组发布到 ASP.NET MVC Controll

    ajax - 将 .ajax() 与 JSONP 一起使用的基本示例?

    python - JSON解码错误: Expecting value: line 1 column

    jquery - 如何使用 jQuery/JavaScript 解析 JSON 数据?

    jquery - 将数组传递给 $.ajax() 中的 ajax 请求

    javascript - 打印 JSON 解析的对象?

    json - 使用jq根据对象中变量的值选择对象

    java - Java 中的 pretty-print JSON

    json - 如何在构建 JSON 字符串时转义特殊字符?