How do we query for a particular fields in an array element inside a json string
The column datatype is JSONB
Sample json
{ "data" : [
{ "begin" : "..." },
{ "inter" : "..." },
{ "inter" : "..." },
{ "skip" : ".." },
{ "inter" : "..." },
{ "final": ".."}
}
We need to find the values of "inter" in above json data string
I tried
select colum_name ->> 'data' ->> 1 ->> 'inter'
but the index is not limited to one value , rather range of values as inter key can be anywhere in the list
2
Answers
Try below query that uses
jsonb_array_elements(your_column->'data')
to unnest the array elements of the JSONB data, allowing us to iterate over each element. Then, the->>
operator is used to extract the text value of the ‘inter’ key from these elements. AWHERE
clause is included to filter out elements without the ‘inter’ key and to ensure that the operation is only performed on array data types.Flatten/unnest the JSON column array using
jsonb_array_elements
and a lateral join, filter by "inter
attribute exists".