Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL 5.7 : convert simple JSON_ARRAY to rows

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  |
+-----+
like image 467
Jibeji Avatar asked Feb 16 '20 14:02

Jibeji


People also ask

Does MySQL 5.7 support JSON data type?

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.

Does MySQL 5.6 support JSON data type?

Yes, however, Domo's MySQL 5.6 environment predates JSON parsing support which was introduced in MySQL 5.7 and expanded in MySQL8.

Can we convert JSON array to string?

Stringify a JavaScript ArrayUse the JavaScript function JSON.stringify() to convert it into a string.

Does MySQL have Jsonb?

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.


1 Answers

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:

  • Find some impossibly complex SQL solution. This is almost always the wrong way to solve the problem, because you end up with code that is too expensive to maintain.
  • Fetch the JSON array as-is, and explode it in application code.
  • Normalize your data so you have one value per row, instead of using JSON arrays.

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.

like image 174
Bill Karwin Avatar answered Oct 19 '22 16:10

Bill Karwin