H
H
hbrmdc2015-12-17 10:39:32
PostgreSQL
hbrmdc, 2015-12-17 10:39:32

How to get JSON object from PostgreSQL?

PostgreSQL 9.4
How to get data like this:

parentTableFirstProp: 'string',
parentToChildReference: [
    {childTableFirstProp: 'another string'},
    {childTableFirstProp: 'yet another string'}
}]

instead of this:
[{
    parentTableFirstProp: 'string',
    childTableFirstProp: 'another string',
},{
    parentTableFirstProp: 'string',
    childTableFirstProp: 'yet another string'
}]

Is it possible to do this with some simple query, or do you need to do 2+ SELECTs each time and then nest one response into another using aliases?
Thank you for your time!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
H
hbrmdc, 2015-12-18
@hbrmdc

select row_to_json(t)
from (
select "ParentTable"."parentTableFirstProp", (
select array_to_json(array_agg(row_to_json(child)))
  from (
    select "childTableFirstProp"
    from "ChildTable"
    where "ChildTable"."id"="ParentTable"."parentToChildReference"
  ) child

  ) as parentToChildReference
from "ParentTable"
) t

K
Kirill, 2015-12-17
@kshvakov

Something like this:

select row_to_json(j.*) from (

  select  'string' as parentTableFirstProp, to_json(

    (
    select to_json(array_agg(r.*)) from (
      select s as childTableFirstProp from (select unnest('{another string,yet another string}'::text[]) as s) _
    )as r
    )
  ) as parentToChildReference

) as j

R
romy4, 2015-12-17
@romy4

above is not according to the json standard, so postgres returns everything correctly to you. redo it so that everything is perceived according to the standard

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question