python - 将字典转换为 JSON 数组时出现 TypeError

标签 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

最佳答案

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

print(json.dumps(info))

关于python - 将字典转换为 JSON 数组时出现 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23956353/

相关文章:

python - 从训练有素的分类器中获取结果 - 图像处理

java - 如何在另一个自定义 JsonSerializer Jackson 中调用 JsonSerializer

arrays - 如何在 Swift 4 中选择要反序列化的 JSON 数组

python - 从字典 python 中选择一个键

c# - 简单的json检索

python - OpenCV Python - 将特定颜色设置为图像区域

python - PyODBC 查询的 Unicode 问题

Python嵌套字典理解

java - 读取服务器发送的数据时出现空字符串

python - 从重复项 JSON 中获取不同的值