I have a simple table with a JSON_ARRAY column like that:
+----+---------+
| id | content |
+----+---------+
| 1 | [3, 4] |
| 2 | [5, 6] |
+----+---------+
I want to list all the content references for a specific id
SELECT JSON_EXTRACT(content, '$') as res FROM table WHERE id=1
But I'd like the result to be in rows:
+-----+
| res |
+-----+
| 3 |
| 4 |
+-----+
As of MySQL 5.7. 8, MySQL supports a native JSON data type defined by RFC 7159 that enables efficient access to data in JSON (JavaScript Object Notation) documents.
Yes, however, Domo's MySQL 5.6 environment predates JSON parsing support which was introduced in MySQL 5.7 and expanded in MySQL8.
Stringify a JavaScript ArrayUse the JavaScript function JSON.stringify() to convert it into a string.
JSON has been supported by MySQL since version 5.7. 8. MySQL stores JSON in binary form, like PostgreSQL's JSONB format. This means that the JSON is always validated, because it's always parsed, and it's efficiently accessed as it's optimized into keys with values and arrays.
You can do this in MySQL 8.0 with JSON_TABLE():
select r.res from mytable,
json_table(mytable.content, '$[*]' columns (res int path '$')) r
where mytable.id = 1
I tested on MySQL 8.0.17, and this is the output:
+------+
| res |
+------+
| 3 |
| 4 |
+------+
If you use a version older than MySQL 8.0, you have these options:
I often find questions on Stack Overflow about using JSON in MySQL that convince me that this feature has ruined MySQL. Developers keep using it inappropriately. They like that it makes it easy to insert semi-structured data, but they find that it makes querying that data far too complex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With