You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This approach allows you to easily iterate over JSON arrays and access their elements in a tabular format, which can be very useful for further processing or joining with other tables in your database.
371
366
372
367
### Iterating over a JSON object
373
368
374
-
MySQL provides the `JSON_TABLE` function to iterate over JSON objects:
369
+
The `JSON_TABLE` function can also be used to iterate over JSON objects:
375
370
376
371
```sql
377
372
SELECT jt.*
@@ -388,6 +383,23 @@ FROM JSON_TABLE(
388
383
| "Alice" |
389
384
| "1990-01-15" |
390
385
386
+
#### Iterating over key-value pairs
387
+
388
+
You can use the `JSON_KEYS()` function to retrieve the list of keys in a JSON object as a JSON array,
389
+
then use that array to iterate over the keys of a JSON object:
390
+
391
+
```sql
392
+
SELECT json_key, json_extract(json_str, CONCAT(''$.'', json_key)) as json_value
393
+
FROM
394
+
(select ''{"name": "Alice", "birthday": "1990-01-15"}'' as json_str) AS my_json,
395
+
JSON_TABLE(json_keys(json_str), ''$[*]'' COLUMNS (json_key JSON PATH ''$'')) AS json_keys;
396
+
```
397
+
398
+
| json_key | json_value |
399
+
|----------|------------|
400
+
| name | Alice |
401
+
| birthday | 1990-01-15 |
402
+
391
403
### Querying JSON data
392
404
393
405
MySQL allows you to query JSON data using the `->` and `->>` operators:
0 commit comments