JSON Keypaths
Some built-in JSON functions operate on sub-elements in their first argument.
The following table and values were used in the examples:
CREATE TABLE greek_alpha (ltr_name text(25));DESC greek_alpha;
+----------+------+-----+-----+---------+-------+ | Field | Type | Null| Key | Default | Extra | +----------+------+-----+-----+---------+-------+ | ltr_name | text | YES | | NULL | | +----------+------+-----+-----+---------+-------+
INSERT INTO greek_alpha (ltr_name) VALUES ('{"posIds": [{ "text": "alpha" },{ "text": "beta" },{ "text": "gamma" },{ "text": "delta" }]}');
In the following examples, both of the SELECT
queries will have the same result, "gamma".
SELECT JSON_EXTRACT_JSON(ltr_name, 'posIds', 2, 'text') FROM greek_alpha;
+---------------------------------------------------+ | JSON_EXTRACT_JSON(ltr_name, 'posIds', 2, 'text') | +---------------------------------------------------+ | "gamma" | +---------------------------------------------------+ SELECT ltr_name::posIds::`2`::text FROM greek_alpha; +------------------------------+ | ltr_name::posIds::`2`::text | +------------------------------+ | "gamma" | +------------------------------+
In the UPDATE
query, the built-in function JSON_
takes a keypath.
UPDATE greek_alpha SET ltr_name = JSON_DELETE_KEY(ltr_name, 'posIds', 2);SELECT * FROM greek_alpha;
+----------------------------------------------------------------+ | ltr_name | +----------------------------------------------------------------+ | {"posIds":[{"text":"alpha"},{"text":"beta"},{"text":"delta"}]} | | +----------------------------------------------------------------+
Note
For more info on JSON operators ::
, ::$
, and ::%
, see Accessing Fields in a JSON Object.
The following JSON functions accept keypaths:
Last modified: April 3, 2023