Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to insert new value in the middle of a JSON array?

I have a JSON type field in my table, which has a value like this

[1, 3]

and I want to insert another value in the middle of the array, using something like a json splice function (I know it doesn’t exist)

/* JSON_ARRAY_SPLICE(array, start, deleteCount, itemToInsert) */
JSON_ARRAY_SPLICE('[1, 3]', 1, 0, 2)
>>> [1, 2, 3]

I’m using php and I can make a function in order to do it, but i’m looking for a mysql solution. Is there a way I can achieve this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

mysql> set @j = '[1, 3]';

mysql> select json_array_insert(@j, '$[1]', 2) as new_j;
+-----------+
| new_j     |
+-----------+
| [1, 2, 3] |
+-----------+
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading