0

One of my columns contains the below array. I just need the order_lookup_code. How do I do this?

vendor_provided_data
{"vendor_data": [{"order_id": 10000, "shipment_id": 20000, "order_lookup_code": "fr_30000dd"}]}
3
  • If the array contains multiple elements, do you want multiple rows in the result? Commented May 13, 2021 at 5:38
  • No. Preferably just another column next to it showing just the order_lookup_code Commented May 13, 2021 at 5:43
  • Do you have an upper limit of the number of elements? You can't have dynamic columns in a SQL query. So you need to write a query with a pre-defined number of columns Commented May 13, 2021 at 6:26

2 Answers 2

2

If you want multiple columns, you need one expression per column, e.g.

select vendor_provided_data #>> '{vendor_data, 0, order_lookup_code}' as code_1,
       vendor_provided_data #>> '{vendor_data, 1, order_lookup_code}' as code_2,
       vendor_provided_data #>> '{vendor_data, 2, order_lookup_code}' as code_3,
       ...
from the_table

The #>> operator extracts a "nested" element from a JSON value, along a "path" where each element of the array specifies a step in the path. The same could be achieved using multiple -> operators. {vendor_data, 0, 'order_lookup_code'} is equivalent to -> 'vendor_data' -> 0 -> 'order_lookup_code'

If multiple rows are OK, you can use jsonb_array_elements()

select t.id, --<< whatever columns you want from the table
       vd.item ->> 'order_lookup_code' as lookup_code
from the_table t
  cross join jsonb_array_elements(t.vendor_provided_data -> 'vendor_data') as vd(item)

If you are on Postgres 12 or later, you could extract all codes as a single JSON array:

select jsonb_path_query_array(vendor_provided_data, '$.vendor_data[*].order_lookup_code') as all_codes
from the_table
Sign up to request clarification or add additional context in comments.

2 Comments

select vendor_provided_data #>> '{vendor_data, 0, "order_lookup_code"}' as code_1
This works! I just have to use a double quotation mark for order_lookup_code. Postgres was giving me a syntax error. Thank you!
0

I assume the vendor_provided_data is your jsonb column . This query would return you all records of table shipment with selection of order_lookup_code .

select jsonb_array_elements(vendor_provided_data->'vendor_data')->>'order_lookup_code' order_lookup_code
from shipment 
where 1 = 1

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.