[英]How to convert JSON into rows in Postgres stored procedure
I am trying to write stored procedure in Postgres.我正在尝试在 Postgres 中编写存储过程。 But I have data as JSON in Postgres like the below.
但是我在 Postgres 中有 JSON 的数据,如下所示。
{
"identifiers":
[
{
"identifierType": "VIN",
"value": "L608"
},
{
"identifierType": "VIN",
"value": "L604"
}
]
Now I need to convert the above JSON into separate columns and rows using Postgres:现在我需要使用 Postgres 将上述 JSON 转换为单独的列和行:
identifierType value
-----------------------------
VIN L608
VIN L604
Please help.请帮忙。 Thanks.
谢谢。
There's no need for a stored procedure to do this.不需要存储过程来执行此操作。 In fact, a stored procedure couldn't return those data, although a function could.
事实上,存储过程无法返回这些数据,尽管 function 可以。
Here's an example to return this data from a query:这是从查询中返回此数据的示例:
-- 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);
EDIT:编辑:
Here's a function that can do this.这是一个可以做到这一点的 function。 Note the a procedure will not work because you can't return data from a procedure.
请注意,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.