postgresql字符串到jsonb\u each\u text()

zbwhf8kr  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(374)

我在postgresql中将此字符串(字符可变)作为行值:

{'img_0': 'https://random.com/xxxxxx.jpg', 'img_1': 'https://random.com/yyyyyy.jpg', 'img_2': 'https://random.com/zzzzzz.jpg'}

我正在尝试json_eact_text(),但不知道怎么做。我曾尝试对其使用jsonb(),然后使用jsonb each(),但出现以下错误:

ERROR:  cannot call jsonb_each on a non-object

我的问题:

WITH 
test AS (
    SELECT to_jsonb(value) as value FROM attribute_value WHERE id = 43918
)

SELECT jsonb_each(value) FROM test
k5ifujac

k5ifujac1#

您的文本值不是有效的json。json需要双引号( " )分隔线。
如果你的数据一直是错误的,这将通过修改你的文本来实现:

with t (sometext) as (
  values ($${'img_0': 'https://random.com/xxxxxx.jpg', 'img_1': 'https://random.com/yyyyyy.jpg', 'img_2': 'https://random.com/zzzzzz.jpg'}$$)
)
select jsonb_each_text(replace(sometext, '''', '"')::jsonb)
  from t;

            jsonb_each_text            
---------------------------------------
 (img_0,https://random.com/xxxxxx.jpg)
 (img_1,https://random.com/yyyyyy.jpg)
 (img_2,https://random.com/zzzzzz.jpg)
(3 rows)

要将其拆分为列:

with t (sometext) as (
  values ($${'img_0': 'https://random.com/xxxxxx.jpg', 'img_1': 'https://random.com/yyyyyy.jpg', 'img_2': 'https://random.com/zzzzzz.jpg'}$$)
)
select j.*
  from t
 cross join lateral jsonb_each_text(replace(sometext, '''', '"')::jsonb) as j;

  key  |             value             
-------+-------------------------------
 img_0 | https://random.com/xxxxxx.jpg
 img_1 | https://random.com/yyyyyy.jpg
 img_2 | https://random.com/zzzzzz.jpg
(3 rows)

相关问题