【问题标题】:Python json.dumps TypeError: Object of type 'set' is not JSON serializable , when trying convert from variable , working when hardcodedPython json.dumps TypeError: Object of type 'set' is not JSON serializable ,当尝试从变量转换时,硬编码时工作
【发布时间】:2020-12-07 12:16:11
【问题描述】:

我尝试从 python 中的变量创建 JSON 字符串,但我得到了奇怪的行为

当我对 pro 对象进行硬编码时,此结果格式良好:

rev_= 'Package ID: bbbbb\nBuild\nnumber: 154\nBuilt\n'
s_ver_str_ = 'bbb.bbb.3.3.98'
result = json.dumps({"rev": rev_, "s_ver_str": s_ver_str_, "pro": {'message': 'no verstion found'}})

但是当我尝试将 pro 对象设置为变量时会返回错误:

    rev_= 'Package ID: bbbbb\nBuild\nnumber: 154\nBuilt\n'
    s_ver_str_ = 'bbb.bbb.3.3.98'
    pro_ = "'message': 'no verstion found'"
    result = json.dumps({"rev":rev_,"s_ver_str":s_ver_str_,"pro": { pro_ }})

收到此错误:

Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.3.2\plugins\python-ce\helpers\pydev\pydevd.py", line 1434, in _exec
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.3.2\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Dev/python/new_tester/simple_main.py", line 19, in <module>
    result = json.dumps({"rev":rev_,"s_ver_str":s_ver_str_,"pro": { pro_ }})
  File "C:\Python36-64\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "C:\Python36-64\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Python36-64\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:\Python36-64\lib\json\encoder.py", line 180, in default
    o.__class__.__name__)
TypeError: Object of type 'set' is not JSON serializable

【问题讨论】:

  • "pro": { pro_ } {} 周围的 pro_ 把它变成一个集合。

标签: python json python-3.x


【解决方案1】:

您的问题是您的代码没有按照您的预期执行。 Python 中的大括号用于dictset 对象。

如果你这样使用它们:

{'message': 'Hello World'}

创建了dict 类型的对象。

但是,如果你这样使用它们:

{'Hello World'}

创建了set 类型的对象。

您的 pro 变量是单个 str 变量,因此,请执行以下操作:

pro_ = {"'message': 'no verstion found'"}

将创建一个只有一个值的set - 您的字符串。


如果您想将该集合序列化到 json 中,可以使用 list(_pro) 执行此操作,但这没有任何意义,因为它还会包含您的引号。

【讨论】:

    【解决方案2】:

    pro_ 是一个字符串文字,而您希望它是一个字典,就像在您的第一个示例中一样。

    rev_= 'Package ID: bbbbb\nBuild\nnumber: 154\nBuilt\n'
    s_ver_str_ = 'bbb.bbb.3.3.98'
    pro_ = {"message": "no verstion found"}
    result = json.dumps({"rev":rev_,"s_ver_str":s_ver_str_,"pro": pro_ })
    

    【讨论】:

      猜你喜欢
      • 2021-03-21
      • 2023-02-24
      • 1970-01-01
      • 2013-11-25
      • 2019-05-06
      • 2019-10-09
      • 2021-03-02
      • 2014-10-14
      • 1970-01-01
      相关资源
      最近更新 更多