data_garden data_garden - 16 days ago 3
Python Question

Python - JSON TypeError: key 'tuple' is not a string

I have this

dictionary
, where
keys
are
tuples
:

tags = {'playlist': {('seen live', 21): 1, ('indie', 46): 1, ('british rock', 2): 1, ('alternative rock', 19): 1, ('00s', 2): 1, ('english', 2): 1, ('brit pop', 2): 1, ('pop rock', 2): 1, ('90s', 10): 1, ('classic rock', 3): 1, ('hard rock', 2): 1, ('Manchester', 4): 1, ('favorites', 1): 1, ('british', 61): 1, ('rock', 89): 1, ('alternative', 53): 1, ('punk', 1): 1, ('male vocalists', 2): 1, ('britpop', 100): 1, ('pop', 7): 1, ('UK', 4): 1, ('oasis', 9): 1, ('indie rock', 12): 1, ('Britrock', 3): 1, ('england', 1): 1, ('brit rock', 2): 1}}


I am trying to upload this to directory with
json
format, with:

with open(path, 'w') as t:
json.dump(tags, t)


but it seems that
tuples
as
keys
are not allowed using
json.dump()
, because I get this traceback:

TypeError: key ('seen live', 21) is not a string


Is there a workaround this?

Answer

If you want to save the data as JSON you need to convert it into a form JSON can use. I have no idea what your data is or whether this is the best option, but as an example I convert the tuple into a string that can be split out later. So, for instance, ('alternative rock', 19) becomes 'alternative rock 19'. You may want some other format, but this is one reasonable way to do it.

>>> tags = {'playlist': {('seen live', 21): 1, ('indie', 46): 1, ('british rock', 2): 1, ('alternative rock', 19): 1, ('00s', 2): 1, ('english', 2): 1, ('brit pop', 2): 1, ('pop rock', 2): 1, ('90s', 10): 1, ('classic rock', 3): 1, ('hard rock', 2): 1, ('Manchester', 4): 1, ('favorites', 1): 1, ('british', 61): 1, ('rock', 89): 1, ('alternative', 53): 1, ('punk', 1): 1, ('male vocalists', 2): 1, ('britpop', 100): 1, ('pop', 7): 1, ('UK', 4): 1, ('oasis', 9): 1, ('indie rock', 12): 1, ('Britrock', 3): 1, ('england', 1): 1, ('brit rock', 2): 1}}
>>> tags['playlist'] = {'{} {}'.format(*k):v for k,v in tags['playlist'].items()}
>>> print(tags['playlist'])
{'alternative 53': 1, 'oasis 9': 1, 'alternative rock 19': 1, 'british 61': 1, 'male vocalists 2': 1, 'brit rock 2': 1, 'england 1': 1, 'punk 1': 1, 'pop rock 2': 1, '00s 2': 1, 'seen live 21': 1, 'indie 46': 1, 'hard rock 2': 1, 'favorites 1': 1, 'Britrock 3': 1, 'english 2': 1, 'indie rock 12': 1, '90s 10': 1, 'classic rock 3': 1, 'brit pop 2': 1, 'pop 7': 1, 'british rock 2': 1, 'rock 89': 1, 'UK 4': 1, 'Manchester 4': 1, 'britpop 100': 1}
>>> json.dumps(tags)
'{"playlist": {"alternative 53": 1, "oasis 9": 1, "alternative rock 19": 1, "british 61": 1, "male vocalists 2": 1, "brit rock 2": 1, "england 1": 1, "punk 1": 1, "pop rock 2": 1, "00s 2": 1, "seen live 21": 1, "indie 46": 1, "hard rock 2": 1, "favorites 1": 1, "Britrock 3": 1, "english 2": 1, "indie rock 12": 1, "90s 10": 1, "classic rock 3": 1, "brit pop 2": 1, "pop 7": 1, "british rock 2": 1, "rock 89": 1, "UK 4": 1, "Manchester 4": 1, "britpop 100": 1}}'