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

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

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

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


        
相关标签:
7条回答
  • Modifying the accepted answer above, I wrote a function to handle dictionaries of arbitrary depth:

    def stringify_keys(d):
        """Convert a dict's keys to strings if they are not."""
        for key in d.keys():
    
            # check inner dict
            if isinstance(d[key], dict):
                value = stringify_keys(d[key])
            else:
                value = d[key]
    
            # convert nonstring to string if needed
            if not isinstance(key, str):
                try:
                    d[str(key)] = value
                except Exception:
                    try:
                        d[repr(key)] = value
                    except Exception:
                        raise
    
                # delete old key
                del d[key]
        return d
    
    0 讨论(0)
提交回复
热议问题