How to get value from JSON with dynamic key in Postgres
·
Answer a question
The following query gets all key names that are needed from a jsonb
object. Basically, getting all key names that contain 'foo' from a column called 'objects'.
SELECT keys
FROM (
SELECT jsonb_object_keys(objects) as keys
from table
) as testvalues
WHERE keys LIKE '%foo%';
Once I get the set of key names, I want to access the status
field of that object as follows
SELECT objects->'hello_foo'->'status' FROM table
However, I still can't find a way to go through the set of key names in the first query and dynamically access the status
field.
What would be the best implementation?
Answers
You can use jsonb_each()
to extract all elements as key/value pairs. Then you can filter by the key
s and access the value
objects:
demo:db<>fiddle
SELECT
*,
objects.value -> 'status'
FROM
t,
jsonb_each(mydata) objects
WHERE objects.key::text LIKE '%foo%'
更多推荐
所有评论(0)