简体   繁体   中英

How to convert nested dictonary to json in Python?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM