1

I have create table with Json datatype field in PostgreSQL.

Also i have inserted data with multiple object in json data

like this

[
    {
        "Type": "1",
        "Amount": "1000",
        "Occurrence": 2,
        "StartDate": "1990-01-19",
        "EndDate": "1999-04-03"
    },
    {
        "Type": "2",
        "Amount": "2000",
        "Occurrence": 2,
        "StartDate": "1984-11-19",
        "EndDate": "1997-09-29"
    }
]

Now i have to retrieve my data as per below formate in single row like string_agg() function output.

Type    Amount
1--2    1000-2000

also i have checked inbuilt function for json in PostgreSQL (https://www.postgresqltutorial.com/postgresql-json/) but not find any solutions for the same.

2
  • Which Postgres version are you using? Commented Apr 7, 2021 at 5:55
  • i am using Postgres 10.4 Commented Apr 7, 2021 at 5:58

1 Answer 1

4

You will have to unnest the array and aggregate the individual keys:

The following assumes you have some kind of primary key column on the table (in addition to your JSON column):

select t.id, 
       string_agg(x.element ->> 'Type', '-') as types,
       string_agg(x.element ->> 'Amount', '-') as amounts
from the_table t
  cross join jsonb_array_elements(t.data) as x(element)
group by t.id;

jsonb_array_elements() extracts each array element and the main query then aggregates that back per ID using string_agg().

The above assumes your column is defined with the type jsonb (which it should be). If it is not, you need to use json_array_elements() instead.

Online example

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @a_horse_with_no_name, perfect answer as what i need, Also one quick question should i use json or jsonb for this type of data?
Quote from the manual "In general, most applications should prefer to store JSON data as jsonb"
@a_horse_with_no_name, what if two json columns in same table, currently its duplicate data with use of cross join, i have updated in code here - dbfiddle.uk/… for this scenario

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.