0

I am using Postgres and I am trying to get all the elements in the array that's has a keys statusCode and place the values into an array so I can display it.

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

the result should be ["S01","SF02"]

0

You can expand and then aggregate back the jsonb field. The WITH section is only here for example purposes.

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
  • Can you example where to sale and the exampleData is coming from? – Corey Carrington Apr 11 at 16:01
  • exampleData in the WITH section is just here to make a working example. If you copy-paste this as a query it will work as is. I made the assumption that systemStatuses is the name of a field in your table, so I guess you would have to replace exampleData with your table name, but without more context it is difficult to tell :) – Creaforge Apr 11 at 16:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.