[英]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.