Reputation: 423
I have a MySQL JSON field with this content.
{"name": "Safari", "os": "Mac", "resolution": "1920x1080"}
{"name": "Firefox", "os": "PC", "resolution": "1920x1080"}
{"name": "Chrome", "os": "PC", "resolution": "1920x1080"}
I can get all browser names with this query.
SELECT browser->'$.name' browser FROM mytable;
Result = Safari, Firefox, Chrome
But how do I write a query that will give me "name", "os" and "resolution" as the result?
Result = name, os, resolution
Upvotes: 2
Views: 2552
Reputation: 147166
You can use JSON_KEYS
to get a JSON array with the key names in it (which you would then need to parse in your application):
SELECT JSON_KEYS('{"name": "Safari", "os": "Mac", "resolution": "1920x1080"}')
Output:
["os", "name", "resolution"]
To get separate rows with the keys, you'd need MySQL 8+ and JSON_TABLE
:
SELECT *
FROM JSON_TABLE(JSON_KEYS('{"name": "Safari", "os": "Mac", "resolution": "1920x1080"}'),
'$[*]' COLUMNS (key_name VARCHAR(20) PATH '$')
) AS k
Output:
key_name
os
name
resolution
To apply this to a table, you would JOIN
the JSON_TABLE
code above to the table and use the JSON column name in place of the JSON string e.g.
SELECT DISTINCT k.key_name
FROM test t
JOIN JSON_TABLE(JSON_KEYS(t.j),
'$[*]' COLUMNS (key_name VARCHAR(20) PATH '$')
) AS k
Upvotes: 3
Reputation: 133370
select the related json attribute name
SELECT browser->'$.name' name, browser->'$.os' os, browser->'$.resolution' resolution
FROM mytable;
and if you need distinct result add the distinct clause
SELECT DISTINCT browser->'$.name' name, browser->'$.os' os, browser->'$.resolution' resolution
FROM mytable;
Upvotes: 0