0

I have Sample Data

 set @j = '[{"id": 1, "title": "Mohan"}, 
            {"id": 2, "title": "Rama"}, 
            {"id": 3, "title": "IP Mana"}]';
  Select REPLACE(REPLACE(REPLACE(JSON_EXTRACT(@j, '$**.*'),"[",""),"]",""),'"','') AS Name_List from  tbl_employee 

I'm getting Data Like this :

    NameList
 1, Mohan, 2, Rama, 3, IP Mana

I'm trying to get output like this :

NameList
 1 : Mohan, 2 : Rama, 3 : IP Mana

Can any one Suggest me .

2
  • Which version of MySQL are you running? Commented Apr 22, 2020 at 13:00
  • @GMB MYSQL 8.0.13 but i need to execute in Lower versions also Commented Apr 22, 2020 at 13:01

1 Answer 1

1

In MySQL 8.0, you can use json_table() for this:

select id, title
from json_table(
    @j,
    '$[*]'
    columns (id int path '$.id', title varchar(20) path '$.title')
) t;

Or if you want the results as a scalar value:

select group_concat(id, ' : ', title separator ', ') res
from json_table(
    @j,
    '$[*]'
    columns (id int path '$.id', title varchar(20) path '$.title')
) t;

In earlier versions, you would typically use a table of numbers and json_extract():

select 
    json_extract(@j, concat('$[', n.n, '].id')) id,
    json_extract(@j, concat('$[', n.n, '].title')) title
from (select 0 n union all select 1 union all select 2 union all select 3) n
where json_extract(@j, concat('$[', n, ']')) is not null
Sign up to request clarification or add additional context in comments.

8 Comments

it is there in the table column how can I implement this in table
@mohan111: select t.id, t.title from mytable x cross join json_table( x.j, '$[*]' columns (id int path '$.id', title varchar(20) path '$.title') ) t;
it is giving me error . I have Employee Column in that JSon Data is there . Select JSON_EXTRACT(@j, '$**.*') AS Name_List from tbl_employee
@mohan111: what is JSON_EXTRACT(@j, '$**.*') supposed to be? This does not come from the queries I provided you with.
I will check with above provided code and rearrange my script and get back to you
|

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.