将字典转换为JSON数组时的TypeError

时间:2014-05-30 13:57:45

标签: python json dictionary

如何使用python字典,其中键和值是字符串并将其转换为JSON字符串。

这就是我现在所拥有的:

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")

它给了我这个错误

  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

1 个答案:

答案 0 :(得分:71)

您正在尝试序列化类型对象dict,而不是info。转储正确的变量:

print(json.dumps(info))