2

I have a table with a column that has JSON value. This column is so clustered and unable to get detailed information from the column.

   Company     User
    A   [{"Name":"Mark","email":"mark.com","password":"password"},{"Name":"Keith","email":"Keith.com","password":"password"}]
    B   [{"Name":"Anna","email":"anna.com","password":"password"},{"Name":"Lewis","email":"Lewis.com","password":"password"}]
    C   [{"Name":"Bill","email":"bill.com","password":"password"},{"Name":"Stuart","email":"stuart.com","password":"password"}]

Is there any way we can break the column as below in a select statement

Company User_1_name User_1_email User_1_password User_2_name User_2_email User_2_password
A         Mark      mark.com       password        Keith      Keith.com     password
B         Anna      anna.com       password        Lewis      Lewis.com     password
C         Bill      bill.com       password        Stuart     stuart.com    password
3
  • What is the datatype of the column? Is it text or is it jsonb? Commented Aug 19, 2020 at 11:43
  • The datatype is "character varying" Commented Aug 19, 2020 at 11:52
  • Updated my answer, below, to perform the necessary casting. Commented Aug 19, 2020 at 11:55

1 Answer 1

4

Since the column is not defined as jsonb or json per your comment, you will need to cast to make this work:

select company, 
       (user::jsonb)->0->>'Name' as user_1_name,
       (user::jsonb)->0->>'email' as user_1_email,
       (user::jsonb)->0->>'password' as user_1_password,       
       (user::jsonb)->1->>'Name' as user_2_name,
       (user::jsonb)->1->>'email' as user_2_email,
       (user::jsonb)->1->>'password' as user_2_password
  from your_table;

If the number of users per row varies, then you will need to add as many columns as necessary to capture the maximum size.

If any of the rows has invalid json in the user column, then this will not work.

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

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.