Postgresql 字符串到 jsonb_each_text()

Postgresql string to jsonb_each_text()

我将这个字符串(字符变化)作为 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() 它,但不知道该怎么做。 我已经尝试了 to_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

您的文本值无效 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)