PostgreSQL:我如何将一列的json值替换为另一列?

sczxawaw  于 2023-03-12  发布在  PostgreSQL
关注(0)|答案(2)|浏览(267)

我没能找到解决这个问题的办法。
假设我有一张这样的table

with tmp_table(json_row, message) as (
    values 
    ('{"key1": 1, "key2":"first"}'::jsonb, 'this ${key2} is a test of ${key1}'),
    ('{"key1": 2, "key2":"second"}', 'this ${key2} is a test'),
    ('{"key1": 3, "key2":"third"}', 'this ${key1} is a test of ${key2}')
)
select * from tmp_table

如何从另一列的json值替换外部参数,以使预期结果为

先谢了!
编辑:我希望使用regex-replace来查找${}之间的内容

cpjpxq1n

cpjpxq1n1#

您可以将regexp_matchesregexp_split_to_tablepattern matching functions组合在一起,创建一个包含每条消息的字符串部分的表--每行包含一个文本部分和一个${…}替换部分,最后一行不包含替换变量。然后string_agg regate将所有部分重新组合到结果中。对表中的每一行使用子查询执行此操作:

SELECT (
  SELECT string_agg(concat(literal, data->>variable[1]), '')
  FROM (
    SELECT
      regexp_split_to_table(message, '\$\{([^}]*)\}') AS literal,
      regexp_matches(message, '\$\{([^}]*)\}', 'g') AS variable
  ) AS parts
) AS result
FROM example

online demo

eni9jsuy

eni9jsuy2#

试试这个:

with tmp_table(json_row, message) as (
    values 
    ('{"key1": 1, "key2":"first"}'::jsonb, 'this ${key2} is a test of ${key1}'),
    ('{"key1": 2, "key2":"second"}'::jsonb, 'this ${key2} is a test'),
    ('{"key1": 3, "key2":"third"}'::jsonb, 'this ${key1} is a test of ${key2}')
)
select json_row,replace(replace(message,'${key1}', json_row->>'key1'),'${key2}', json_row->>'key2') as message from tmp_table

db<>fiddle
输出

相关问题