如何从jsonb对象数组中提取值?

时间:2019-04-11 14:19:37

标签: arrays postgresql jsonb

我正在使用Postgres,并且尝试获取具有键statusCode的数组中的所有元素,并将值放入数组中以便可以显示它。

"systemStatuses": [
        {
            "changedBy": "monsjenni557",
            "timeStamp": 1554151540.9612856,
            "statusCode": "S01",
            "statusDescription": "Received"
        },
        {
            "changedBy": "monsjenni557",
            "timeStamp": 1554151546.2600567,
            "statusCode": "SF02",
            "statusDescription": "Request Validation Fail"
        }
    ]

结果应为["S01","SF02"]

1 个答案:

答案 0 :(得分:0)

您可以展开,然后聚合回jsonb字段。 WITH部分仅出于示例目的。

WITH exampleData AS (
    SELECT '[
        {
            "changedBy": "monsjenni557",
            "timeStamp": 1554151540.9612856,
            "statusCode": "S01",
            "statusDescription": "Received"
        },
        {
            "changedBy": "monsjenni557",
            "timeStamp": 1554151546.2600567,
            "statusCode": "SF02",
            "statusDescription": "Request Validation Fail"
        }
    ]'::jsonb as regionSales
)

SELECT (
    SELECT jsonb_agg( sale -> 'statusCode')
    FROM jsonb_array_elements(regionSales) AS sale
)

FROM exampleData