Search code examples
postgresqljsonbpostgresql-10postgresql-json

Extract elements from JSON array and return them as concatenated string


A PostgreSQL 10 table contains JSON data like (here an SQL Fiddle):

[
    {
        "col": 7,
        "row": 12,
        "value": 3,
        "letter": "A"
    },
    {
        "col": 8,
        "row": 12,
        "value": 10,
        "letter": "B"
    },
    {
        "col": 9,
        "row": 12,
        "value": 1,
        "letter": "C"
    },
    {
        "col": 10,
        "row": 12,
        "value": 2,
        "letter": "D"
    }
]

How to extract only the "letter" values and concatenate them to a string like

ABCD

I suppose at the end I should use the ARRAY_TO_STRING function, but which JSON function to use for extracting the "letter" values to an array?

UPDATE:

Got a tip at the very helpful PostgreSQL mailing list too:

SELECT string_agg(x->>'letter','') FROM json_array_elements(

'[{"col": 7, "row": 12, "value": 3, "letter": "A"}, {"col": 8, "row": 12, "value": 10, "letter": "B"}, {"col": 9, "row": 12, "value": 1, "letter": "C"}, {"col": 10, "row": 12, "value": 2, "letter": "D"}]'::json

) x;

Solution

  • Use jsonb_array_elements() and string_agg():

    with my_table(json_data) as (
    values(
    '[
        {
            "col": 7,
            "row": 12,
            "value": 3,
            "letter": "A"
        },
        {
            "col": 8,
            "row": 12,
            "value": 10,
            "letter": "B"
        },
        {
            "col": 9,
            "row": 12,
            "value": 1,
            "letter": "C"
        },
        {
            "col": 10,
            "row": 12,
            "value": 2,
            "letter": "D"
        }
    ]'::jsonb)
    )
    select string_agg(value->>'letter', '')
    from my_table
    cross join lateral jsonb_array_elements(json_data)
    
     string_agg 
    ------------
     ABCD
    (1 row)