如何将 JSON 转换为 Postgres 存储过程中的行
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
请帮忙!谢谢
不需要存储过程来执行此操作。事实上,存储过程不能 return 这些数据,尽管函数可以。
下面是一个 return 来自查询的数据的示例:
-- 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);
这是 fiddle。
编辑:
这里有一个函数可以做到这一点。请注意,该过程将不起作用,因为您无法 return 来自过程的数据。
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;
已更新 fiddle。
我正在尝试在 Postgres 中编写存储过程。但我在 Postgres 中的数据为 JSON,如下所示。
{
"identifiers":
[
{
"identifierType": "VIN",
"value": "L608"
},
{
"identifierType": "VIN",
"value": "L604"
}
]
现在我需要使用 Postgres 将上面的 JSON 转换成单独的列和行:
identifierType value
-----------------------------
VIN L608
VIN L604
请帮忙!谢谢
不需要存储过程来执行此操作。事实上,存储过程不能 return 这些数据,尽管函数可以。
下面是一个 return 来自查询的数据的示例:
-- 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);
这是 fiddle。
编辑:
这里有一个函数可以做到这一点。请注意,该过程将不起作用,因为您无法 return 来自过程的数据。
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;
已更新 fiddle。