简体   繁体   English

如何从 Postgres 的 json 列中提取键和值?

[英]How to extract key and value from json column in Postgres?

I want to add key-value pairs extracted from json column to table with Postgresql.我想使用 Postgresql 将从 json 列中提取的键值对添加到表中。

I have an items_table with uid and data column in json with multiple pairs.我在 json 中有一个带有 uid 和 data 列的 items_table 多对。 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.我尝试应用文档中提到的 jsonb_object_keys,但是出现错误。

     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.错误函数 jsonb_object_keys(字符变化)不存在提示:没有函数匹配给定的名称和参数类型。 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 列:

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?如何实现上述输出?

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. 是一个 db<>fiddle。

You can use json_each_text() method to easily split jsonb type column to two seperate columns :您可以使用json_each_text()方法轻松地将jsonb类型列拆分为两个单独的列:

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 :或更直接地使用cross join

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

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM