web-dev-qa-db-fra.com

TypeError lors de la conversion du dictionnaire en tableau JSON

Comment prendre un dictionnaire python où les clés et les valeurs sont des chaînes et les convertir en chaîne JSON.

Voici ce que j'ai en ce moment:

import json

def create_simple_meeting(subject, startDate, endDate, location, body):
    info = dict()
    if(subject != ""):
        info["subject"] = subject
    if(startDate != ""):
        info["startDate"] = startDate
    if(endDate != ""):
        info["endDate"] = endDate
    if(body != ""):
        info["body"] = body
    if(location != ""):
        info["location"] = location
    print(json.dumps(dict))

create_simple_meeting("This is the subject of our meeting.","2014-05-29 11:00:00","2014-05-29 12:00:00", "Boca Raton", "We should definitely meet up, man")

Et ça me donne cette erreur

  File "/Users/bens/Documents/workspace/Copy of ws1 for py Java playing/opias/robot/libs/playing.py", line 15, in create_simple_meeting
    print(json.dumps(dict))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 243, in dumps
    return _default_encoder.encode(obj)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <type 'dict'> is not JSON serializable
28
Ben Sandler

Vous essayez de sérialiser l'objet type, dict, au lieu de info. Vider la bonne variable:

print(json.dumps(info))
71
Martijn Pieters