0

I want to turn jsonb values into a key-value table within a single statement

My sample code:

CREATE TABLE public.searchdatacache
( querysig text, "values" jsonb );
INSERT INTO searchdatacache (querysig, values)
VALUES 
(
'ytApiSearch://Armageddon trailer',
'[
  {"VideoId"      : "xwseawq"},
  {"Title"        : "Armageddon"},
  {"PublishedAt"  : "2012/01/01"},
  {"Description"  : "Armageddon is a film"},
  {"ChannelTitle" : "Bruce Willis Movies"}
]'
)

SELECT jsonb_array_elements(values) from searchdatacache where querysig =    'ytApiSearch://Armageddon trailer'

returns:

"{"VideoId": "xwseawq"}"
"{"Title": "Armageddon"}"
"{"PublishedAt": "2012/01/01"}"
"{"Description": "Armageddon is a film"}"
"{"ChannelTitle": "Bruce Willis Movies"}"

the data returned by the select statement looks ok so far but now I want to use this select statement within an "INSERT INTO" statement to fill a key-value table.

these records should be filled into a new key-value table:

VideoId      | xwseawq
Title        | Armageddon
PublishedAt  | 2012/01/01
Description  | Armageddon is a film
ChannelTitle | Bruce Willis Movies

thanks in advance Gerald

1 Answer 1

1

Use jsonb_array_elements in the from clause along with jsonb_each_text to get the key value pairs ready to be inserted.

select s.key,s.value
       from searchdatacache cross join lateral
             jsonb_array_elements(values) as j(e)
    cross join lateral jsonb_each_text(j.e) as s(key,value);

Demo

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.