2

I want to add key-value pairs extracted from json column to table with Postgresql.

I have an items_table with uid and data column in json with multiple pairs. Initial table that looks like:

uid | data

1   | {"item1":"string1", "item2":"string2"}
2   | {"item2":"string3", "item5":"string1", "item7":"string5"}
3   | {"item1":"string3", "item4":"string1", "item6":"string8", "item5":"string5"}
4   | {"item1":"string4"}

...

Thus, some items/strings can repeat and fields length can vary as well.

I tried apply jsonb_object_keys, mentioned in documentation, however I occurred an error.

     select jsonb_object_keys(data) 
     from items_table;

ERROR: function jsonb_object_keys(character varying) does not exist Hint: No function matches the given name and argument types. You may need to add explicit type casts.

I would like obtain a table result in following way to get split by items and strings, expanding uid column:

uid | items      | strings

1   | item1      | string1
1   | item2      | string2
2   | item2      | string3
2   | item5      | string1
2   | item7      | string5
3   | item1      | string3
3   | item4      | string1
3   | item6      | string8
3   | item5      | string5
4   | item1      | string4

How is it possible to achieve the above output?

2 Answers 2

2

You can use json_each_text() method to easily split jsonb type column to two seperate columns :

select uid, (js).key as items, (js).value as strings
  from
  (
   select uid, jsonb_each_text(data) as js
     from tab
  ) q 

or more directly by using cross join :

select uid, js.items, js.value as strings
  from tab
 cross join jsonb_each_text(data) as js(items)

Demo

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

Comments

1

You should be able to extract the keys and then the values:

select key, v.j->key
from (values (1, '{"item1":"string1", "item2":"string2"}'::jsonb),
             (2, '{"item2":"string3", "item5":"string1", "item7":"string5"}'::jsonb)
     ) v(id, j) cross join lateral
     jsonb_object_keys(v.j) as key;

Here is a db<>fiddle.

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.