2012-10-04 23 views
6

余米尝试转换以下dict into JSON using json.dumps的字符串:的Json倾销的字典给出了类型错误:密钥必须

{ 
    '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 
} 

但它使我

TypeError : keys must be a string 

我猜的错误可能会被弹出因为字典包含,一些元素,如:

<built-in function id>: '213046588825668' 

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

+3

解决您的数据。 –

回答

11

你可以尝试把它清理干净这样的:

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] 

这将尝试转换不是一个字符串转换为字符串的任意键。任何无法转换为字符串或表示为字符串的键都将被删除。

+0

这完全不是你的错,但这不会做真正的*真正*想要的东西。 –

+0

做了一些修改,但它的工作!非常感谢 –

+4

将函数对象作为字典中的一个键的唯一方法是在某处输入'id'(这是一个内置函数)而不是''id''(这是一个字符串文字)。不要试图用更多的代码来解决现有的bug,也许你应该尝试弄清楚构建字典的代码在哪里混乱了? – Fredrik

-5

也许这将有助于未来的家伙:

strjson = json.dumps(str(dic).replace("'",'"')) 
+0

这是相当丑陋的,并且还会转储json-ish编码数据的json编码,因此json编码会执行一次到多次。 – Herbert

相关问题