【问题标题】:How to concatenate strings to form a json object in Postgres?如何连接字符串以在 Postgres 中形成 json 对象?
【发布时间】:2020-06-03 07:51:28
【问题描述】:

我有一个字符串 coldata->>'f1' 我需要动态发送它以获取 JSON 对象。

我真正想要的是:

RAISE NOTICE 'OBJECT %', fc_data->'firstname'->>'value';

就我而言,我在存储过程中的变量coldata->>'f1' 中动态获取firstname。我需要动态发送密钥以获取值。为此我尝试了以下代码:

RAISE NOTICE 'OBJECT %', ((('fc_data->')::text) || '''' || ((coldata->>'f1')::text) || '''');

显示fc_data1->'firstname',Postgres 将其视为字符串,我想要它的值。所以我尝试将其转换为jsonb,如下所示:

RAISE NOTICE 'OBJECT %', ((('fc_data->')::text) || '''' || ((coldata->>'f1')::text) || '''')::jsonb;

它给了我以下错误:

ERROR:  invalid input syntax for type json
DETAIL:  Token "fc_data" is invalid.

如何将字符串连接为对象的键?

【问题讨论】:

  • @a_horse_with_no_name 不,它是 10.11
  • @a_horse_with_no_name 我已经尝试了一些东西并得到了它的一部分。我只需要将文本转换为 json

标签: json postgresql plpgsql postgresql-10


【解决方案1】:

-> operator for json / jsonbtextint 置于右侧,这可以来自表达式。你可以简单地:

DO
$do$
DECLARE
   coldata jsonb := '{"f1":"firstname"}';
   fc_data jsonb := '{"firstname": {"value":123}}';
BEGIN
   RAISE EXCEPTION 'OBJECT %', fc_data -> (coldata->>'f1') ->> 'value';
END
$do$;

db小提琴here (我把它作为一个例外在小提琴中,我们可以看到它。)

只是像演示的那样添加括号。

【讨论】:

    猜你喜欢
    • 2015-06-06
    • 2012-08-16
    • 1970-01-01
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    • 2016-03-12
    • 2019-03-09
    • 2016-12-21
    相关资源
    最近更新 更多