0

I have a column with the following text data (2 rows):

{"{john,m,25.01.1980}","{steve,m,12.12.1995}","{kate,f,17.04.1990}"}
{"{max,m,26.01.1980}","{sarah,f,18.04.1990}"}

This need to be converted into json like this (2 rows):

[{ "birth_date": 1234567890, "name": "john", "gender": "m" }, { "birth_date": 1234567890, "name": "steve", "gender": "m" }, { "birth_date": 1234567890, "name": "kate", "gender": "f" }]
[{ "birth_date": 1234567890, "name": "max", "gender": "m" }, { "birth_date": 1234567890, "name": "sarah", "gender": "f" }]

I have tried to use UNNEST, row_to_json and json_build_object, but cannot fugure out how to do this.

4
  • are you showing data of one row? Commented Jan 20, 2022 at 14:43
  • @eshirvana, no, this is 2 rows Commented Jan 20, 2022 at 14:45
  • Are your strings such as "{steve,m,12.12.1995}" contained in arrays, or is each row text as well i.e '{"{max,m,26.01.1980}","{sarah,f,18.04.1990}"}'? Commented Jan 20, 2022 at 14:51
  • @Ajax1234 data type - text, so '{"{max,m,26.01.1980}","{sarah,f,18.04.1990}"}' Commented Jan 20, 2022 at 14:53

2 Answers 2

2

You can try this :

SELECT jsonb_agg(jsonb_build_object
                       ('birth_date', split_part(left(d.data, -1), ',', 3) :: date
                       ,'name', split_part(right(d.data, -1), ',', 1)
                       ,'gender', split_part(d.data, ',', 2)))
  FROM your_table AS t
 CROSS JOIN LATERAL unnest(t.your_text_column :: text[]) AS d(data)
 GROUP BY t

see the test result in dbfiddle.

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

Comments

0

here is one way:

select Id
    , json_agg(json_build_object('name', split_part(jsondata, ',',1) , 'gender', split_part(jsondata, ',',2), 'birth_date', split_part(jsondata, ',' ,3))) json_info
from (
select id
,  replace(replace(json_array_elements(replace(replace(info,'{"','["'), '"}','"]')::json) #>> '{}','{',''),'}','') jsondata
from tablename
) t group by id 

db<>fiddle 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.