1

I have table field called values which has a current JSON value of the following:

{"roles": ["1","2","3","4"]}

I also have another table called roles as below

id role_name
1 Admin
2 Finance
3 Payroll
4 Accountant

I am trying to use the JSON_REPLACE function to replace the id numbers in the values JSON string with the role names.

Basically it should have a result like this

{"roles": ["Admin","Finance","Payroll","Account"]}

But I cannot use JSON_REPLACE like JSON_REPLACE('["1","2","3","4"]', '$[0]', Admin, '$[1]', Finance) because the number of IDs and role names may vary differently, that's why I need to know how to do this in a single SELECT statement.

7
  • Did you mean to write: {"roles": ["1","2","3","4"]} ? Commented Jul 13, 2022 at 10:30
  • Oh i'm sorry. Amended @bloodyKnuckles Commented Jul 13, 2022 at 10:33
  • Does this have to be pure MySQL? Commented Jul 13, 2022 at 10:39
  • Yes. strictly MySQL if possible, as other types may cause it to not work. Commented Jul 13, 2022 at 10:42
  • What "other types may cause it to not work" ? Are you saying you don't have have a server-side language like PHP available? Commented Jul 13, 2022 at 10:44

1 Answer 1

2

You can use json_table:

select json_object('role', (select json_arrayagg(r1.role_name) 
  from json_table(t.value, '$.roles[*]' columns(role int path '$')) r 
  join roles r1 on r.role = r1.id)) 
from vals t

See fiddle.

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

3 Comments

I tried the above solution. but it returned me a result of {"roles" : null} instead. Is there a way to replace the current roles JSON string values instead of needing to create an object?
@lyracarat03 Can you share your code in a fiddle?
Hi, sorry I had a slight typo in my code when i was testing. it is working now. Thanks!

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.