0

I have a table called emp with a column called info as type jsonb

now i want to insert data into it from a table

so it looks like this

{
  "birth": {"date": "1980-04-28"},"Name": {"surname": "James","firstname": "Jacob"}
}

I issue the SQL

insert into emp(info)
select 
  row_to_json(x)::jsonb from 
            (select birth_date as date, lastname as surname, given_name as firstname FROM stg.employees) x;

but it returns

{
  "date": "1975-11-29T00:00:00",
  "surname": "James",
  "firstname":"Jaconb"
}

and not

    {
      "birth": {"date": "1980-04-28"},
      "Name": {"surname": "James","firstname": "Jacob"}
    }

could you please point me in the right direction? thank you

1 Answer 1

1
insert into emp(info)
select 
  row_to_json(x)::jsonb from 
            (select jsonb_build_object('date', birth_date) as birth, jsonb_build_object('surname', lastname, 'firstname', given_name) as name FROM stg.employees) x;
Sign up to request clarification or add additional context in comments.

3 Comments

Consider adding an explanation of what you've changed and how this fixes the issue.
thanks Edouard - that worked could you show me how to write it when its nested eg ``` "currentAddress": { "postal": { "type": "Street", "state": "MI", "zipcode": "90801", "number": "1", "StreetName": "First Ave" }, "residential": { "type": "Street", "state": "CA", "zipcode": "50891", "number": "167", "StreetName": "Fifth Ave" } } ```
using row_to_json and/or json_build_object, you have to iterate as many times as the number of json nested objects. In your last example you have three levels so : json_build_object('currentAddress', json_build_object('postal', '{}' :: json, 'residential', json_build_object('type', 'Street', 'state', 'NT', 'suburb', 'Darwin', 'postcode', '0801', 'numberlot', '1', 'StreetName', 'Smith', 'unitDetails', '1')))

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.