0

I want to expand a specific row in my table which has a json column with the followingstructure:

 id|column1      |
---|-------------|
id1|{nested json}|
id2|{nested json}|

Structure of nested JSON is as follows:

{"random_key_1":{"
               known_key_1":"value",
               "known_key_2":"value"
              },
"random_key_2":{"
               known_key_1":"value",
               "known_key_2":"value"
              },
...

I want expand a single row into following format:

my_column_name |known_key_1 |known_key2|
---------------|-----------|----------|
random_key_1   |  value    |  values  |
random_key_2   |  value    |  values  |
2
  • 1
    Hi, interesting, not sure if this might be of interest stackoverflow.com/questions/25978846/… Commented Sep 29, 2020 at 1:19
  • Haha! I tired to build my logic based on this post but the nested part is something that postgres doesn't like :( Commented Sep 29, 2020 at 1:21

1 Answer 1

2

You can use the built-in json_each method to expand your outermost JSON into rows without knowing what the keys are. From that point, you can build the known columns directly.

SELECT col1.key AS my_column_name, 
       col1.value->>'known_key_1' AS known_key_1, 
       col1.value->>'known_key_2' AS known_key_2 
FROM main_table, json_each(column1) col1;

 my_column_name | known_key_1 | known_key_2
----------------+-------------+-------------
 random_key_1   | value1      | value2
 random_key_2   | value3      | value4
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.