2012-10-04 11 views
6

Yo estoy tratando de convertir la siguiente dict into JSON using json.dumps:JSON vertido un diccionario da TypeError: las claves deben ser una cadena

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

Pero me lleva a

TypeError : keys must be a string 

supongo que el error podría estar apareciendo porque el dict contiene, algunos elementos como:

<built-in function id>: '213046588825668' 

¿Puede alguien por favor guíame, con cómo debo retirarme? ove estos elementos del dict?

+3

arreglar los datos. –

Respuesta

11

Se podría tratar de limpiarlo como esto:

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] 

Este tratará de convertir cualquier tecla que no es una cadena de caracteres en una cadena. Cualquier clave que no pueda convertirse en una cadena o representarse como una cadena será eliminada.

+0

No es totalmente tu culpa, pero esto no hará lo que el asker * realmente * quiere. –

+0

¡¡Hice algunas modificaciones, pero funcionó !! Muchas gracias –

+4

La única forma de obtener ese objeto de función como una clave en tu diccionario es escribiendo "id" (que es una función incorporada) en lugar de "id" (que es un literal de cadena) en alguna parte. En lugar de tratar de solucionar el problema existente con más código, ¿debería tratar de averiguar dónde se equivocó el código que crea el diccionario? – Fredrik

-5

Tal vez esto ayudará al individuo siguiente:

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

esto es bastante feo y también descarga una codificación json de los datos codificados json-ish, por lo que la codificación json se ejecuta una vez para muchos. – Herbert

Cuestiones relacionadas