i am storing JSON
data as jsonb
column and searching for specific object by key . Here is my json structure
[
{
"item_tags": ["black", "optional"],
"name": "Keyboard",
"price": 50,
"currency": "USD",
"discount_price": 40
},
{
"item_tags": ["white", "optional"],
"name": "Mouse",
"price": 40,
"currency": "USD",
"discount_price": 30
}
]
sql query select r.data->1 from data_set
gives me the correct result but i would like to get something like select r.data->@name='Mouse' from data_set
Where name would be dynamic irrespective of position of the object inside array.
3
Answers
To achieve this in PostgreSQL with a dynamic search for an object within the JSON array based on the key name, you can use the jsonb_array_elements function, which will flatten the JSON array into individual objects. Then you can filter based on the name key within each object.
You can try this by using the following SQL query:
Explanation:
I think you can just use
jsonb_array_elements
without LATERAL.Output
Example Fiddle
Note : In the fiddle I tested with Lateral, but it returns both Keyboard and Mouse as
name
which is not desired.The
@?
JSONPath operator is quick and flexible. It can speed up even more using a GIN index to get your results quickly andjsonb_path_query()
unpacks each mouse into a separate row. It also makes no assumptions about the structure of thejsonb
value.The
.name
accessor in the jsonpath expression doesn’t mind that it has to first open up an array element before it finds thename
key in it.demo at db<>fiddle