Reputation: 119
I created a nested dictionary in Python like this:
news_output = {'_id': 'd11bd6d0-846f-406d-a8e8-de57ee35fd53',
'Link': ['https://www.marketingweek.com/2019/04/15/ad-blocking-retail-sales-ad-saturation-5-killer-stats-to-start-your-week/'],
'Title': 'Why AI is the key to engaging today’s entitled consumer',
'Entity': {'ORG': 'Coca-Cola', 'GPE': 'UK'},
'Verbs': {0: {'Verb Text': 'is',
'Text Head of the verb': 'ramping',
'Child Word of the verb': []},
1: {'Verb Text': 'ramping',
'Text Head of the verb': 'ramping',
'Child Word of the verb': [Cola, is, up, launches, brings, drink, .]},
2: {'Verb Text': 'brings',
'Text Head of the verb': 'ramping',
'Child Word of the verb': [as, it, mineral]},
'Verb Text': 'brings',
'Text Head of the verb': 'ramping',
'Child Word of the verb': [as, it, mineral]},
'Dependent Words': {0: {'Text': 'Coca-Cola',
'Root Text': 'Cola',
'Dependent Text': 'ramping'},
1: {'Text': 'new product launches',
'Root Text': 'launches',
'Dependent Text': 'ramping'},
2: {'Text': 'it', 'Root Text': 'it', 'Dependent Text': 'brings'},
3: {'Text': 'its mineral',
'Root Text': 'mineral',
'Dependent Text': 'brings'},
4: {'Text': 'drink', 'Root Text': 'drink', 'Dependent Text': 'ramping'},
5: {'Text': 'Aquarius', 'Root Text': 'Aquarius', 'Dependent Text': 'drink'},
6: {'Text': 'the UK', 'Root Text': 'UK', 'Dependent Text': 'to'},
'Text': 'the UK',
'Root Text': 'UK',
'Dependent Text': 'to'},
'Signal': 'weak'}
I tried to convert it into JSON using below code:
json.dumps(news_output)
But I am getting a below error and I am unable to figure out how to write this nested dict into a json file. Any comments will be appreciated..!
File "<ipython-input-138-78c27a14715b>", line 2, in <module>
a = json.dumps(news_output)
File "F:\Python\AnacondaFile\lib\json\__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "F:\Python\AnacondaFile\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "F:\Python\AnacondaFile\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "F:\Python\AnacondaFile\lib\json\encoder.py", line 180, in default
o.__class__.__name__)
TypeError: Object of type 'Token' is not JSON serializable
Upvotes: 0
Views: 259
Reputation: 853
Your error is : TypeError: Object of type 'Token' is not JSON serializable
Cause you forgot quotes in list like [as, it, mineral]
, if "as" is a object you can write it without quotes, but "it" and "mineral" seems like string, so you have to write [as, "it", "mineral"]
I try it like this, and it's work for me.
Upvotes: 1