Python3无法将str转换为dict或json

时间:2018-06-20 01:47:41

标签: python json python-3.x dictionary

r = requests.get(http_get_url, headers=headers)
r = r.text
r = r.replace("true", "True")
z = json.loads(r)

但是,我没有加载json(或python dict),而是得到了:

Traceback (most recent call last):
  File "/home/noir/PycharmProjects/Work_Projects/get_errors.py", line 21, in <module>
    get_errors(id)
  File "/home/noir/PycharmProjects/Work_Projects/get_errors.py", line 17, in get_errors
    z = json.loads(r)
  File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 2 column 26 (char 28)

print(type(r))的结果为<class 'str'>

,将'true'转换为'True'后,print(r)的输出为:

{
    "HasItemsWithCount": True,
    "Collection": [

            {
            "GroupId" : "14",
            "Time" : "5/16/18, 5:02 PM",
            "File" : "[ESCAPE[]]",
            "Message" : "[ESCAPE[Client was restarted during backup, session may be incomplete.]]",
            "Count" : "3"
            },

    ]
}

所以我无法理解为什么 r 的正确格式的字符串无法导入到json中。

此外,如果我获得此输出并通过复制/粘贴将其直接写入python,则变量的类型为dict,向我展示文本在Python中为dict正确设置了格式。所以我不确定为什么json.loads失败。

1 个答案:

答案 0 :(得分:1)

您的替换是反向的:

代替:

= 2*foo - baz

尝试:

value=4475, min=4470, max=4480