Rechercher dans le manuel MySQL

12.17.6 JSON Table Functions

This section contains information about JSON functions that convert JSON data to tabular data. In MySQL 8.0.4 and later, one such function—JSON_TABLE()—is supported.

  • JSON_TABLE(expr, path COLUMNS (column_list) [AS] alias)

    Extracts data from a JSON document and returns it as a relational table having the specified columns. The complete syntax for this function is shown here:

    JSON_TABLE(
        expr,
        path COLUMNS (column_list)
    )   [AS] alias
    
    column_list:
        column[, column][, ...]
    
    column:
        name FOR ORDINALITY
        |  name type PATH string path [on_error] [on_empty]
        |  name type EXISTS PATH string path
        |  NESTED [PATH] path COLUMNS (column_list)
    
    on_error:
        {NULL | ERROR | DEFAULT json_string} ON ERROR
    
    on_empty:
        {NULL | ERROR | DEFAULT json_string} ON EMPTY

    expr: This is an expression that returns JSON data. This can be a constant ('{"a":1}'), a column (t1.json_data, given table t1 specified prior to JSON_TABLE() in the FROM clause), or a function call (JSON_EXTRACT(t1,jsn_data,'$.post.comments')).

    path: A JSON path expression, which is applied to the data source. We refer to the JSON value matching the path as the row source; this is used to generate a row of relational data. The COLUMNS clause evaluates the row source, finds specific JSON values within the row source, and returns those JSON values as SQL values in individual columns of a row of relational data.

    The alias is required. The usual rules for table aliases apply (see Section 9.2, “Schema Object Names”).

    JSON_TABLE() supports four types of columns, described in the following list:

    1. name FOR ORDINALITY: This type enumerates rows in the COLUMNS clause; the column named name is a counter whose type is UNSIGNED INT, and whose initial value is 1. This is equivalent to specifying a column as AUTO_INCREMENT in a CREATE TABLE statement, and can be used to distinguish parent rows with the same value for multiple rows generated by a NESTED [PATH] clause.

    2. name type PATH string_path [on_error] [on_empty]: Columns of this type are used to extract values specified by string_path. type is a MySQL data type. JSON_TABLE() extracts data as JSON then coerces it to the column type, using the regular automatic type conversion applying to JSON data in MySQL. The exact behavior depends on the column type: If the column type is an SQL type, then only a scalar value can be saved in the column. Saving an object or array triggers the on error clause; this also occurs when an error takes place during coercion from the value saved as JSON to the table column, such as trying to save the string 'asd' to an integer column. A missing value triggers the on_empty clause.

      The optional on_error clause determines what JSON_TABLE() does when saving an object or array:

      • NULL ON ERROR: The column is set to NULL; this is the default behavior. If an error occurs during type coercion, a warning is thrown.

      • ERROR ON ERROR: An error is thrown.

      • DEFAULT json string ON ERROR: The json_string is parsed as JSON (provided that it is valid) and stored instead of the object or array. A warning is thrown if the error is caused by type coercion. Column type rules also apply to the default value.

      When a value saved to a column is truncated, such as saving 3.14159 in a DECIMAL(10,1) column, a warning is issued independently of any ON ERROR option. When multiple values are truncated in a single statement, the warning is issued only once.

      The optional on empty clause determines what JSON_TABLE() does in the event that data is missing (depending on type). This clause is also triggered on a column in a NESTED PATH clause when the latter has no match and a NULL complemented row is produced for it. on empty takes one of the following values:

      • NULL ON EMPTY: The column is set to NULL; this is the default behavior.

      • ERROR ON EMPTY: An error is thrown.

      • DEFAULT json_string ON EMPTY: the provided json_string is parsed as JSON, as long as it is valid, and stored instead of the missing value. Column type rules also apply to the default value.

      This query demonstrates the use of the ON ERROR and ON EMPTY options. The row corresponding to {"b":1} is empty for the path "$.a", and attempting to save [1,2] as a scalar produces an error; these rows are highlighted in the output shown.

      1. mysql> SELECT *
      2.     -> FROM
      3.     ->   JSON_TABLE(
      4.     ->     '[{"a":"3"},{"a":2},{"b":1},{"a":0},{"a":[1,2]}]',
      5.     ->     "$[*]"
      6.     ->     COLUMNS(
      7.     ->       rowid FOR ORDINALITY,
      8.     ->       ac VARCHAR(100) PATH "$.a" DEFAULT '999' ON ERROR DEFAULT '111' ON EMPTY,
      9.     ->       aj JSON PATH "$.a" DEFAULT '{"x": 333}' ON EMPTY,
      10.     ->       bx INT EXISTS PATH "$.b"
      11.     ->     )
      12.     ->   ) AS tt;
      13.  
      14. +-------+------+------------+------+
      15. | rowid | ac   | aj         | bx   |
      16. +-------+------+------------+------+
      17. |     1 | 3    | "3"        |    0 |
      18. |     2 | 2    | 2          |    0 |
      19. |     3 | 111  | {"x": 333} |    1 |
      20. |     4 | 0    | 0          |    0 |
      21. |     5 | 999  | [1, 2]     |    0 |
      22. +-------+------+------------+------+
      23. 5 rows in set (0.00 sec)
    3. name type EXISTS PATH path: This column returns 1 if any data is present at the location specified by path, and 0 otherwise. type can be any valid MySQL data type, but should normally be specified as some variety of INT.

    4. NESTED [PATH] path COLUMNS (column_list): This flattens nested objects or arrays in JSON data into a single row along with the JSON values from the parent object or array. Using multiple PATH options allows projection of JSON values from multiple levels of nesting into a single row.

      The path is relative to the parent path row path of JSON_TABLE(), or the path of the parent NESTED [PATH] clause in the event of nested paths.

    Column names are subject to the usual rules and limitations governing table column names. See Section 9.2, “Schema Object Names”.

    All JSON and JSON path expressions are checked for validity; an invalid expression of either type causes an error.

    Each match for the path preceding the COLUMNS keyword maps to an individual row in the result table. For example, the following query gives the result shown here:

    1. mysql> SELECT *
    2.     -> FROM
    3.     ->   JSON_TABLE(
    4.     ->     '[{"x":2,"y":"8"},{"x":"3","y":"7"},{"x":"4","y":6}]',
    5.     ->     "$[*]" COLUMNS(
    6.     ->       xval VARCHAR(100) PATH "$.x",
    7.     ->       yval VARCHAR(100) PATH "$.y"
    8.     ->     )
    9.     ->   ) AS  jt1;
    10.  
    11. +------+------+
    12. | xval | yval |
    13. +------+------+
    14. | 2    | 8    |
    15. | 3    | 7    |
    16. | 4    | 6    |
    17. +------+------+

    The expression "$[*]" matches each element of the array. You can filter the rows in the result by modifying the path. For example, using "$[1]" limits extraction to the second element of the JSON array used as the source, as shown here:

    1. mysql> SELECT *
    2.     -> FROM
    3.     ->   JSON_TABLE(
    4.     ->     '[{"x":2,"y":"8"},{"x":"3","y":"7"},{"x":"4","y":6}]',
    5.     ->     "$[1]" COLUMNS(
    6.     ->       xval VARCHAR(100) PATH "$.x",
    7.     ->       yval VARCHAR(100) PATH "$.y"
    8.     ->     )
    9.     ->   ) AS  jt1;
    10.  
    11. +------+------+
    12. | xval | yval |
    13. +------+------+
    14. | 3    | 7    |
    15. +------+------+

    Within a column definition, "$" passes the entire match to the column; "$.x" and "$.y" pass only the values corresponding to the keys x and y, respectively, within that match. For more information, see JSON Path Syntax.

    NESTED PATH (or simply NESTED; PATH is optional) produces a set of records for each match in the COLUMNS clause to which it belongs. If there is no match, all columns of the nested path are set to NULL. This implements an outer join between the topmost clause and NESTED [PATH]. An inner join can be emulated by applying a suitable condition in the WHERE clause, as shown here:

    1. mysql> SELECT *
    2.     -> FROM
    3.     ->   JSON_TABLE(
    4.     ->     '[ {"a": 1, "b": [11,111]}, {"a": 2, "b": [22,222]}, {"a":3}]',
    5.     ->     '$[*]' COLUMNS(
    6.     ->             a INT PATH '$.a',
    7.     ->             NESTED PATH '$.b[*]' COLUMNS (b INT PATH '$')
    8.     ->            )
    9.     ->    ) AS jt
    10.     -> WHERE b IS NOT NULL;
    11.  
    12. +------+------+
    13. | a    | b    |
    14. +------+------+
    15. |    1 |   11 |
    16. |    1 |  111 |
    17. |    2 |   22 |
    18. |    2 |  222 |
    19. +------+------+

    Sibling nested paths—that is, two or more instances of NESTED [PATH] in the same COLUMNS clause—are processed one after another, one at a time. While one nested path is producing records, columns of any sibling nested path expressions are set to NULL. This means that the total number of records for a single match within a single containing COLUMNS clause is the sum and not the product of all records produced by NESTED [PATH] modifiers, as shown here:

    1. mysql> SELECT *
    2.     -> FROM
    3.     ->   JSON_TABLE(
    4.     ->     '[{"a": 1, "b": [11,111]}, {"a": 2, "b": [22,222]}]',
    5.     ->     '$[*]' COLUMNS(
    6.     ->         a INT PATH '$.a',
    7.     ->         NESTED PATH '$.b[*]' COLUMNS (b1 INT PATH '$'),
    8.     ->         NESTED PATH '$.b[*]' COLUMNS (b2 INT PATH '$')
    9.     ->     )
    10.     -> ) AS jt;
    11.  
    12. +------+------+------+
    13. | a    | b1   | b2   |
    14. +------+------+------+
    15. |    1 |   11 | NULL |
    16. |    1 |  111 | NULL |
    17. |    1 | NULL |   11 |
    18. |    1 | NULL |  111 |
    19. |    2 |   22 | NULL |
    20. |    2 |  222 | NULL |
    21. |    2 | NULL |   22 |
    22. |    2 | NULL |  222 |
    23. +------+------+------+

    A FOR ORDINALITY column enumerates records produced by the COLUMNS clause, and can be used to distinguish parent records of a nested path, especially if values in parent records are the same, as can be seen here:

    1. mysql> SELECT *
    2.     -> FROM
    3.     ->   JSON_TABLE(
    4.     ->     '[{"a": "a_val",
    5.    '>       "b": [{"c": "c_val", "l": [1,2]}]},
    6.     '>     {"a": "a_val",
    7.    '>       "b": [{"c": "c_val","l": [11]}, {"c": "c_val", "l": [22]}]}]',
    8.    ->     '$[*]' COLUMNS(
    9.    ->       top_ord FOR ORDINALITY,
    10.    ->       apath VARCHAR(10) PATH '$.a',
    11.    ->       NESTED PATH '$.b[*]' COLUMNS (
    12.    ->         bpath VARCHAR(10) PATH '$.c',
    13.    ->         ord FOR ORDINALITY,
    14.    ->         NESTED PATH '$.l[*]' COLUMNS (lpath varchar(10) PATH '$')
    15.    ->         )
    16.    ->     )
    17.    -> ) as jt;
    18.  
    19. +---------+---------+---------+------+-------+
    20. | top_ord | apath   | bpath   | ord  | lpath |
    21. +---------+---------+---------+------+-------+
    22. |       1 |  a_val  |  c_val  |    1 | 1     |
    23. |       1 |  a_val  |  c_val  |    1 | 2     |
    24. |       2 |  a_val  |  c_val  |    1 | 11    |
    25. |       2 |  a_val  |  c_val  |    2 | 22    |
    26. +---------+---------+---------+------+-------+

    The source document contains an array of two elements; each of these elements produces two rows. The values of apath and bpath are the same over the entire result set; this means that they cannot be used to determine whether lpath values came from the same or different parents. The value of the ord column remains the same as the set of records having top_ord equal to 1, so these two values are from a single object. The remaining two values are from different objects, since they have different values in the ord column.


Suchen Sie im MySQL-Handbuch

Deutsche Übersetzung

Sie haben gebeten, diese Seite auf Deutsch zu besuchen. Momentan ist nur die Oberfläche übersetzt, aber noch nicht der gesamte Inhalt.

Wenn Sie mir bei Übersetzungen helfen wollen, ist Ihr Beitrag willkommen. Alles, was Sie tun müssen, ist, sich auf der Website zu registrieren und mir eine Nachricht zu schicken, in der Sie gebeten werden, Sie der Gruppe der Übersetzer hinzuzufügen, die Ihnen die Möglichkeit gibt, die gewünschten Seiten zu übersetzen. Ein Link am Ende jeder übersetzten Seite zeigt an, dass Sie der Übersetzer sind und einen Link zu Ihrem Profil haben.

Vielen Dank im Voraus.

Dokument erstellt 26/06/2006, zuletzt geändert 26/10/2018
Quelle des gedruckten Dokuments:https://www.gaudry.be/de/mysql-rf-json-table-functions.html

Die Infobro ist eine persönliche Seite, deren Inhalt in meiner alleinigen Verantwortung liegt. Der Text ist unter der CreativeCommons-Lizenz (BY-NC-SA) verfügbar. Weitere Informationen auf die Nutzungsbedingungen und dem Autor.

Referenzen

  1. Zeigen Sie - html-Dokument Sprache des Dokuments:en Manuel MySQL : https://dev.mysql.com/

Diese Verweise und Links verweisen auf Dokumente, die während des Schreibens dieser Seite konsultiert wurden, oder die zusätzliche Informationen liefern können, aber die Autoren dieser Quellen können nicht für den Inhalt dieser Seite verantwortlich gemacht werden.
Der Autor Diese Website ist allein dafür verantwortlich, wie die verschiedenen Konzepte und Freiheiten, die mit den Nachschlagewerken gemacht werden, hier dargestellt werden. Denken Sie daran, dass Sie mehrere Quellinformationen austauschen müssen, um das Risiko von Fehlern zu reduzieren.

Inhaltsverzeichnis Haut