0

I have a table of data with and id column and a jsonb column with object data:

id (int) data (jsonb)

I'm querying the data like this

select row_to_json(t)
from (
    select id, data from accounts
) t;

which gets me data that looks like this:

{
   "id":3,
   "data":
   {
      "emailAddress": "[email protected]", 
      "mobileNumbers": ["5559991212"]
   }
}

I would like to merge the data field into the main record set, I basically want the keys in the data node into the main record:

{
   "id":3,
   "emailAddress": "[email protected]", 
   "mobileNumbers": ["5559991212"]
}

1 Answer 1

1

You can use

SELECT jsonb_set(data, '{id}', to_jsonb(id))
FROM accounts;

I cannot help remarking that a table with just a primary key and a jsomb column seems like a problematic database design to me.

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

5 Comments

Thanks for the feedback, I've significantly simplified the table design by omitting other columns. I'm taking an approach that stores objects in jsonb, but denormalizing the data into columns for searching and joining to other tables of objects.
Ah, that sounds better.
This is the correct answer and I've marked it as such. Can I ask for a bit more advice, that builds off of the first question?
I have two related tables to the accounts table that are 1..n, I want to grab that data and nest it inside the data from the account table. Having trouble, I can get the other arrays of data to be adjacent, but not nested: SELECT jsonb_set(data, '{id}', to_jsonb(id)) account, ( SELECT array_to_json(array_agg(jsonb_set(data, '{id}', to_jsonb(id)))) FROM people WHERE account_id = accounts.id ) people FROM accounts;
Sounds like a second question.

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.