0

I have a table filled with json objects. There is only one column 'data'.

I would like to convert this table into one with multiple columns for all the keys in the json objects.

For example,

Right now my table is like this:

data
{'key1': 'value1', 'key2': 'value2'}
{'key1': 'value3', 'key2': 'value4'}

But I would like it like this:

key1 key2
value1 value2
value3 value4

I'm not trying to query it in this way, I would like to completely create a new table in the format that I've shown above.

I can try running:

INSERT INTO new_table 
SELECT data -> 'key1', data -> 'key2' 
FROM old_table

But since my json objects have hundreds of columns this may be inefficient. Is there a more efficient way to do so? Any help or suggestions is appreciated.

1 Answer 1

2

maybe this way is more simple?

select t.*
from yourtable
cross join json_to_record(jsoncol) t(key1 text,key2 text,key3 text,...);

on the second thought , if you already have a table that matches the columns from your json , you can do this:

create table newTable (key1 text, key2 text , ...);

select t.*
from yourtable
cross join json_populate_record(null::newTable,jsoncol) t;
Sign up to request clarification or add additional context in comments.

1 Comment

This command results in an out of memory error and when I limit to 1000 for example, it doesn't add anything to the new table. select count(*) returns 0 rows. I do have the new table with all the columns already created though.

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.