I have a JSON column, telework
, stored in Postgres which looks like
"{ ...,
"biweeklyWeek1-locationMon": "alternative",
"biweeklyWeek1-locationTues": "agency",
"biweeklyWeek1-locationWeds": "alternative",
"biweeklyWeek1-locationThurs": "alternative",
"biweeklyWeek1-locationFri": "alternative",
... ,
"biweeklyWeek2-locationMon": "alternative",
"biweeklyWeek2-locationTues": "agency",
"biweeklyWeek2-locationWeds": "alternative",
"biweeklyWeek2-locationThurs": "alternative",
"biweeklyWeek2-locationFri": "alternative",
... }"
I need to count the number of occurrences of "alternative" in the biweeklyWeek1-location*
fields and biWeeklyWeek2-location*
fields separately and select these two as separate fields in the main query. It’s possible that the values in these fields could be filled, blank (""
), or null
. Also, it’s possible that these fields are partially or completely missing in the JSON.
select a.id,
a.name,
a.telework->>??? as alternativePerWeek1,
a.telework->>??? as alternativePerWeek2,
...
Strangely enough, even when I do the following single example with ->
a hard-coded ID, I get a NULL result even though I see that it shouldn’t be NULL:
select telework, telework->'biweeklyWeek1-locationMon' from ets.agreement_t where id = 24763;
2
Answers
Assumption: telework JSON column contains a list of (key, value) pair and key is in the format
biweekly?-location???
.The output is like:
EDIT: Per comment, json_each() can also be used in SELECT
Output:
You can also parse the
key_value
column to get what you needYou can use a scalar sub-query after unnesting the JSON using
json_each()
Btw: the recommended data type to store JSON is
jsonb