assuming I have json column which look something like:
-- first row:
{
"a": {
"x": {"name": "ben", "success": true},
"y": {"name": "sarah", "success": true},
"z": {"name": "john", "success": false}
}
}
-- second row:
{
"a": {
"m": {"name": "issac", "success": true},
"n": {"name": "jack", "success": true},
}
}
I want to select all rows which any of their a.<something>.success is not true.
in my Example - first row will be selected, second row will be filtered.
As you can see all jsons start with common key a, but under it there are unknown number of "childs" with unknown names ('x', 'y', 'z', 'm', 'n').
under each child with unknown name - there is a common known key I'd like to filter by: success.
Question is how Can filter such rows?
I got to something I could not complete:
SELECT * FROM my_table WHERE json_col::json -> 'a' -> <don't know what to put here> -> 'success' = true
You can explode the
jsonvalue withjson_each()into key:value pairs and check the values. That will work in anexistscondition: demo"a": {
"x": {"name": "ben", "success": true},
"y": {"name": "sarah", "success": true},
"z": {"name": "john", "success": false}
}
}
If you switch from
jsontojsonbyou'll be able to speed up the search with a GIN index, get rid of insignificant whitespace, deduplicate and order your keys, get more functions and operators to choose from, like@@(that, and otherjsonpath-related features are supported from version 12 onwards):If you're on version 11, its support ended on 2023-11-09. Consider upgrading.
To get the name(s) that had
.success<>true, you can usejsonb_path_query():