Json转储dict抛出TypeError:keys必须是一个字符串

Vir*_*put 15 python json simplejson

我试图转换以下内容dict:

 {
     'post_engaged': 36,
     'post_impressions': 491,
     'post_story': 23,
     'comment_count': 6,
     'created_time': '03:02 AM, Sep 30, 2012',
     'message': 'Specialities of Shaktis and Pandavas. \n While having power, why there isn\\u2019t',
     < built - in function id > : '471662059541196',
     'status_type': 'status',
     'likes_count': 22
 } {
     'post_engaged': 24,
     'text': '30 Sept 2012 Avyakt Murlli ( Dual Voice )',
     'post_story': 8,
     'comment_count': 3,
     'link': 'http:\\/\\/www.youtube.com\\/watch?v=VGmFj8g7JFA&feature=youtube_gdata_player',
     'post_impressions': 307,
     'created_time': '03:04 AM, Sep 30, 2012',
     'message': 'Not available',
     < built - in function id > : '529439300404155',
     'status_type': 'video',
     'likes_count': 7
 } {
     'post_engaged': 37,
     'post_impressions': 447,
     'post_story': 22,
     'comment_count': 4,
     'created_time': '03:11 AM, Sep 30, 2012',
     'message': '30-09-12 \\u092a\\u094d\\u0930\\u093e\\u0924:\\u092e\\u0941\\u0930\\u0932\\u0940 \\u0913\\u0',
     < built - in function id > : '471643246209744',
     'status_type': 'status',
     'likes_count': 20
 } {
     'post_engaged': 36,
     'post_impressions': 423,
     'post_story': 22,
     'comment_count': 0,
     'created_time': '03:04 AM, Sep 29, 2012',
     'message': 'Essence: Sweet children, whenever you have time, earn the true income. Staying i',
     < built - in function id > : '471274672913268',
     'status_type': 'status',
     'likes_count': 20
 } {
     'post_engaged': 16,
     'text': 'Essence Of Murli 29-09-2012',
     'post_story': 5,
     'comment_count': 2,
     'link': 'http:\\/\\/www.youtube.com\\/watch?v=i6OgmbRsJpg&feature=youtube_gdata_player',
     'post_impressions': 291,
     'created_time': '03:04 AM, Sep 29, 2012',
     'message': 'Not available',
     < built - in function id > : '213046588825668',
     'status_type': 'video',
     'likes_count': 5
 }
Run Code Online (Sandbox Code Playgroud)

但它引导我

TypeError : keys must be a string
Run Code Online (Sandbox Code Playgroud)

我想错误可能会弹出,因为dict包含,一些元素,如:

 <built-in function id>: '213046588825668'
Run Code Online (Sandbox Code Playgroud)

有人可以指导我,我应该如何从字典中删除这些元素?

big*_*ind 19

您可以尝试像这样清理它:

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]
Run Code Online (Sandbox Code Playgroud)

这将尝试将任何非字符串的键转换为字符串.任何无法转换为字符串或表示为字符串的键都将被删除.

  • 将该函数对象作为字典中的键的唯一方法是在某处键入`id`(这是一个内置函数)而不是``id"`(这是一个字符串文字).您可以尝试找出构建字典的代码在哪里混乱,而不是尝试用更多代码解决现有错误? (6认同)
  • 虽然这个答案被接受和赞成,但实际上在设计和实现上都是完全错误的。对于阅读此答案的任何人:_不要这样做_。 (2认同)

Nol*_*way 8

修改上面接受的答案,我写了一个函数来处理任意深度的字典:

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
Run Code Online (Sandbox Code Playgroud)


bru*_*ers 5

我知道这是一个古老的问题,它已经有一个公认的答案,但遗憾的是,公认的答案是完全错误的。

这里真正的问题是生成 dict 的代码使用内置id函数作为键而不是文字 string "id"。因此,简单、明显且唯一正确的解决方案是从源头修复此错误:检查生成 dict 的代码,并替换id"id".