How to count the unique nested key/values in a json in postgres?
Each user record has a json column called hobby_years which is structured like below but differs from user to user.
Example hobby_years value for a user:
{
"soccer": {
"2006": 1,
"2007": 1
},
"skiing": {},
"basketball": {
"2006": 1,
"2016": 1,
"2017": 1,
"2018": 1
},
"painting": {
"2008": 1,
"2009": 1,
"2014": 1,
"2015": 1,
"2016": 1
}
}
I'd like to know how many unique years exist across one or more specific hobbies. Ie: soccer and basketball - which should return 5.
Alternatively, I have the option to structure data as below if it would make this activity easier
{
"soccer": [2006, 2007],
"skiing": [],
"basketball": [2006, 2016, 2017, 2018],
"painting": [2008, 2009, 2014, 2015, 2016]
}
Is this possible?