[英]How to convert JSON into rows in Postgres stored procedure
我正在尝试在 Postgres 中编写存储过程。 但是我在 Postgres 中有 JSON 的数据,如下所示。
{
"identifiers":
[
{
"identifierType": "VIN",
"value": "L608"
},
{
"identifierType": "VIN",
"value": "L604"
}
]
现在我需要使用 Postgres 将上述 JSON 转换为单独的列和行:
identifierType value
-----------------------------
VIN L608
VIN L604
请帮忙。 谢谢。
不需要存储过程来执行此操作。 事实上,存储过程无法返回这些数据,尽管 function 可以。
这是从查询中返回此数据的示例:
-- Set up the test data
CREATE TABLE test (data json);
INSERT INTO test VALUES ('{"identifiers":
[
{
"identifierType": "VIN",
"value": "L608"
},
{
"identifierType": "VIN",
"value": "L604"
}
]}');
SELECT "identifierType", value
FROM test
CROSS JOIN json_to_recordset(data->'identifiers') as x("identifierType" text, value text);
这是一个小提琴。
编辑:
这是一个可以做到这一点的 function。 请注意,a 过程将不起作用,因为您无法从过程中返回数据。
CREATE OR REPLACE FUNCTION convert_my_json(p_data json)
RETURNS TABLE (
"identifierType" text,
"value" text
)
AS $$
SELECT * FROM json_to_recordset(p_data->'identifiers') as x("identifierType" text, value text);
$$
LANGUAGE SQL
IMMUTABLE;
更新了小提琴。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.