将包含对象数组的json传递给PostgreSQL函数会抛出格式错误的数组文字.意外的数组元素 [英] Passing json containing array of objects to PostgreSQL function throws malformed array literal. Unexpected array element
本文介绍了将包含对象数组的json传递给PostgreSQL函数会抛出格式错误的数组文字.意外的数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的PostgreSQL函数,我想将复杂的JSON传递给:
I have a simple PostgreSQL function I want to pass complex JSON to:
CREATE OR REPLACE FUNCTION foo(sync_data json)
RETURNS json AS
$body$
DECLARE
...
END;
$body$ LANGUAGE plpgsql;
使用类似这样的名称进行调用:
Calling it with something like this:
SELECT foo('{"deviceId":1,"shops":[{"id":1},{"id":2}]}':: json);
SELECT foo('{"deviceId": 1, "shops": [{"id": 1}, {"id": 2}]}'::json);
给我以下错误:
- 错误:格式不正确的数组文字:"{" id:1}"
- 详细信息:意外的数组元素.
- 上下文:SQL语句中的PL/pgSQL函数foo(json)第8行
- SQL状态:22P02
我需要传递复杂的JSON作为参数,其中包含对象数组.
I need to pass complex JSON as a parameter, containing arrays of objects.
谢谢!
PS:这是完整的功能文本:
PS: Here is the full function text:
CREATE OR REPLACE FUNCTION foo(sync_data json)
RETURNS json AS
$body$
DECLARE
res_json json;
device_id integer;
shops json ARRAY;
BEGIN
SELECT json_extract_path(sync_data, 'deviceId') INTO device_id;
SELECT json_array_elements(json_extract_path(sync_data, 'shops')) INTO shops;
SELECT json_build_object('devId', device_id) INTO res_json;
RETURN res_json;
END;
$body$ LANGUAGE plpgsql;
推荐答案
问题出在函数内部的语法上.解析对象数组并将其分配给JSON ARRAY的正确语法:
The problem was with the syntax inside the function. The correct syntax for parsing array of objects and assigning it to json ARRAY:
CREATE OR REPLACE FUNCTION foo(sync_data json)
RETURNS json AS
$body$
DECLARE
res_json json;
device_id integer;
shops json ARRAY;
BEGIN
SELECT json_extract_path(sync_data, 'deviceId') INTO device_id;
shops := ARRAY(SELECT json_array_elements(sync_data->'shops'));
SELECT json_build_object('Dev_id', device_id, 'shop1', shops[1], 'shop2', shops[2]) INTO res_json;
RETURN res_json;
END;
$body$ LANGUAGE plpgsql;
感谢 eurotrash 和阿贝里斯托(Abelisto)!
这篇关于将包含对象数组的json传递给PostgreSQL函数会抛出格式错误的数组文字.意外的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文