0

Input Json

{
"orderId": "order1",
"fulfillerId":"ful1",
"orderDetailsUrl":"het",
"items":[{
        "decorationTechnology":"laserEngraving",
        "itemId":"item1",
        "productName":"Test Sku for Oracle testing"
    },
    {
        "decorationTechnology":"laserEngraving",
        "itemId":"item2",
        "productName":"Test Sku for Oracle testing"
    }
  ]
}

Expected Output JSON

{
   "fulfillerIds":[
      "ful1"
   ],
   "orderIds":[
      "order1"
   ],
   "itemIds":[
       "item1",
        "item2"
   ]
}

Need to form above expected JSON tried to use row_to_json() and jsonb_array_elements() but couldn't get the expected output

2
  • Which Postgres version are you using? Commented Nov 13, 2020 at 14:49
  • version 11.8 @a_horse_with_no_name Commented Nov 17, 2020 at 4:59

2 Answers 2

1

If you are using Postgres 12 or later, you can use SQL/JSON path queries:

select jsonb_build_object(
         'orderIds', jsonb_path_query_array(the_column, '$.orderId'), 
         'fulfillerIds', jsonb_path_query_array(the_column, '$.fulfillerId'),
         'itemIds', jsonb_path_query_array(the_column, '$.items[*].itemId')
       ) as filtered
from the_table;
Sign up to request clarification or add additional context in comments.

1 Comment

Since I am using version 11.8 this might not work for me @a_horse_with_no_name
1

With earlier versions it works with concatenation and building arrays:

WITH t1 AS
    (
        SELECT '{ "orderId": "order1", "fulfillerId":"ful1", "orderDetailsUrl":"het", "items":[{ "decorationTechnology":"laserEngraving", "itemId":"item1", "productName":"Test Sku for Oracle testing" }, { "decorationTechnology":"laserEngraving", "itemId":"item2", "productName":"Test Sku for Oracle testing" } ] } '::jsonb AS field
    )
SELECT jsonb_build_object('orderId', json_build_array (field->>'orderId')) || jsonb_build_object('fulfillerId', json_build_array (field->>'fulfillerId')) || jsonb_build_object('orderDetailsUrl', json_build_array (field->>'orderDetailsUrl')) AS jsonb_result
FROM t1
;

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.