0

Hi i'm using jsonb_agg for create array of objects. But when i want to create it with multiple json im getting this error.

ERROR:  function jsonb_agg(json, json) does not exist

This is what im trying to do

SELECT 
    station.id AS "objectID",
    station.name AS "objectName",
    station.activity,
    'Station'::text AS unit,
    jsonb_agg(
     json_build_object('key'::text, 'value'::text),
     json_build_object('key'::text, 'value'::text),
     ...
    ) AS "childrenList"
    FROM eqp_stations station

Is there any way to merge multiple json into array of objects

I hard coded json key and value pairs but I am going to fill these areas later.

Expected Json object like

{
 "objectId":123,
 "objectName":"blabla",
 "unit":"Station",
 "childrenList": [
   {"key":"value"},
   {"key":"value"},
   ...
  ]
 
}
5
  • it's pretty obvious that you have a jsonb function with arguments returning json values. You might try json(b)_build_object functions as arguments... Commented Mar 15, 2022 at 18:23
  • Post how the expected json looks like and explain why are 'key' and 'value' hardcoded? Commented Mar 15, 2022 at 18:30
  • I will fill the key value pairs with join statements. ı added expected output @SalmanA Commented Mar 15, 2022 at 19:21
  • 1
    I suppose json_agg could be replaced with jsonb_build_array and that is is, assuming you know the number of children in advance. Commented Mar 15, 2022 at 19:42
  • How are we supposed to answer the question now if you don't finish asking it until "later"? Commented Mar 16, 2022 at 14:38

1 Answer 1

1
select 
    jsonb_agg(t1.*)  
from (
    SELECT 
        station.id AS "objectID",
        station.name AS "objectName",
        station.activity,
        'Station'::text AS unit,
        jsonb_build_array( 
            json_build_object('key'::text, 'value'::text),
            json_build_object('key'::text, 'value'::text)
        ) AS "childrenList"
    FROM 
        eqp_stations station
) t1
Sign up to request clarification or add additional context in comments.

Comments

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.