0

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;

1 Answer 1

1

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) 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you... Why wouldn't the following work? select string_agg( jsonb_array_elements( '[{"col": 7, "row": 12, "value": 3, "letter": "A"}, {"col": 8, "row": 12, "value": 10, "letter": "B"}]'::jsonb ) ->> 'letter', '' );
It's a limitation of using a set returning function as an argument of an aggregate function. In cases like that use SRF in the FROM clause,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.