8

I recently found time to upgrade to MySQL 5.7 and I am testing the new JSON functions. So far, pretty awesome!

I have a use case where I need to access the last element in a JSON array. Its easy to retrieve an element when you know the ordinal like this:

SELECT `json_field`->"$.my_array[0]" from `my_table` where `id` = 1;

But in the case when you don't know how many elements you have, this is not available to you. Now, you can find out (and store) how many elements there are like this:

set @arrayLength = (SELECT JSON_LENGTH(`json_field`->"$.my_array") from `my_table` where `id` = 1);

But when you go to use the variable, you do not get a result.

SELECT `json_field`->"$.my_array[@arrayLength - 1]" from `my_table` where `id` = 1;

Has anyone solved a similar problem with MySQL 5.7 yet?

2 Answers 2

12

Since MySQL 8 it's much easier:

`json_field`->> '$[last]'

Other useful examples here

Note: doesn't work in MariaDB

Sign up to request clarification or add additional context in comments.

8 Comments

Beat me to it by 2 hours :)
Be careful it is not working in mariadb. I had to rewrite a bunch of code after migration
Thanks for the insight. I've been thinking a lot about migrating from MySQL8 to Maria, it has a lot of features that I need. Would you recommend the migration overall, are you happier with Maria? Maria claims better performance, Is it true?
I had a bug in mySQL and the only way I found to fix it was the migration to mariadb. I haven't tested it's performance before and after. I'm just happy that bug has gone.
last word doesn't work in mariadb. JSON_EXTRACT/CONCAT/JSON_LENGTH work well
|
9
SELECT JSON_EXTRACT(`json_field`,CONCAT("$.my_array[",JSON_LENGTH(`json_field` ->> '$.my_array')-1,"]")) from `my_table` where `id` = 1;

found here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.