【问题标题】:How to convert JSON into rows in Postgres stored procedure如何将 JSON 转换为 Postgres 存储过程中的行
【发布时间】:2021-07-14 15:01:30
【问题描述】:

我正在尝试在 Postgres 中编写存储过程。但我在 Postgres 中有 JSON 格式的数据,如下所示。

{
    "identifiers": 
        [
            {
                "identifierType": "VIN",
                "value": "L608"
            },
            {
                "identifierType": "VIN",
                "value": "L604"
            }
       ]

现在我需要使用 Postgres 将上述 JSON 转换为单独的列和行:

identifierType        value
-----------------------------
  VIN                  L608
  VIN                  L604

请帮忙!谢谢。

【问题讨论】:

    标签: arrays json postgresql stored-procedures


    【解决方案1】:

    不需要存储过程来执行此操作。事实上,存储过程无法返回这些数据,尽管函数可以。

    这是一个从查询中返回此数据的示例:

    -- 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

    编辑:

    这是一个可以做到这一点的函数。请注意,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;
    

    更新fiddle

    【讨论】:

    • 有没有办法为此创建一个存储过程并调用该过程?
    • @pavithra 我用示例函数更新了答案和小提琴。
    • @Jeremy 是否可以在同一个函数中将这些检索到的 JSON 列用于我的选择查询?查询 1:选择 json_to_recordset 查询 2:选择从查询 1 检索的列的查询。(我想在同一个函数中同时使用查询 1 和查询 2,但从查询 2 返回结果)
    • 可能吗?最好打开一个新问题并包括您试图获得的结果。我无法从你的描述中看出你想要完成什么。
    猜你喜欢
    • 2014-06-10
    • 2020-10-12
    • 1970-01-01
    • 2020-09-28
    • 2013-10-10
    • 2022-12-05
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    相关资源
    最近更新 更多