Json dumping a dict throws TypeError: keys must be a string

前端 未结 7 1212
余生分开走
余生分开走 2020-12-09 10:20

I am attempting to convert the following dict into JSON using json.dumps:

 {
     \'post_engaged\': 36,
     \'post_impressions\':          


        
7条回答
  •  隐瞒了意图╮
    2020-12-09 10:47

    You could try to clean it up like this:

    for key in mydict.keys():
      if type(key) is not str:
        try:
          mydict[str(key)] = mydict[key]
        except:
          try:
            mydict[repr(key)] = mydict[key]
          except:
            pass
        del mydict[key]
    

    This will try to convert any key that is not a string into a string. Any key that could not be converted into a string or represented as a string will be deleted.

提交回复
热议问题