【问题标题】:passing array as key pair in json format to function pgsql将数组作为 json 格式的密钥对传递给函数 pgsql
【发布时间】:2021-12-25 08:16:55
【问题描述】:

我创建了一个接受 json 的函数。这是查询

CREATE OR REPLACE FUNCTION public.data_get(
    data json)
    RETURNS SETOF json 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
DECLARE
        declare _text text;
        
    BEGIN
    -- get fields data from json - https://www.postgresql.org/docs/9.3/functions-json.html
    _text = data::json#>>'{text}';

这就是我调用这个函数的方式

select * from data_get ('{"text":"my"}'::json) as info; 

这很好用

现在我想传递数组元素,所以我添加了这样的变量

DECLARE
        declare 
           _text text;
           _ids bigint[];

并像这样从 json 访问

_ids = data::json#>>'{ids}';

但是当我调用这个函数时

select * from data_get ('{"text":"","ids":[1]}'::json) as info;

它显示

ERROR:  malformed array literal: "[1]"
DETAIL:  Missing "=" after array dimensions.
CONTEXT:  PL/pgSQL function posts_get(json) line 18 at assignment
SQL state: 22P02

如何调用这个函数?

【问题讨论】:

    标签: sql arrays postgresql


    【解决方案1】:

    Postgres 不做从 json 数组到 postgres 数组的隐式转换。

    你需要使用自己的函数:

    CREATE OR REPLACE FUNCTION public.json_to_int_array(json)
     RETURNS integer[]
     LANGUAGE sql
    AS $function$
    SELECT array_agg(v::int) FROM json_array_elements_text($1) g(v)
    $function$
    
    postgres=# SELECT public.json_to_int_array(('{"text":"","ids":[1, 2, 3]}'::json)->'ids');
    ┌───────────────────┐
    │ json_to_int_array │
    ╞═══════════════════╡
    │ {1,2,3}           │
    └───────────────────┘
    (1 row)
    
    

    【讨论】:

      猜你喜欢
      • 2019-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-07
      相关资源
      最近更新 更多