实验验证:
我是经过重重实验,才知道,json.loads(string)的string中的key必须使用双引号的。
json_txt = "{'doors': [[{'pointDown': {'x': 3307.0001220703125, 'y': 2367.75}, 'pointUp': {'x': 3307.0001220703125, 'y': 408.0}, 'weight': 0.912015974521637, 'detect_bottom': 1, 'detect_door': 0, 'balconydoor': 0}, {'pointDown': {'x': 4672.0001220703125, 'y': 2331.0}, 'pointUp': {'x': 4672.0001220703125, 'y': 408.0}, 'weight': 0.912015974521637, 'detect_bottom': 1, 'detect_door': 0, 'balconydoor': 0}]] }"
json.loads(json_txt)
就会报如下错误:
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 14 (char 13)
但是把里面的单引号替换为双引号:
json_txt = "{'doors': [[{'pointDown': {'x': 3307.0001220703125, 'y': 2367.75}, 'pointUp': {'x': 3307.0001220703125, 'y': 408.0}, 'weight': 0.912015974521637, 'detect_bottom': 1, 'detect_door': 0, 'balconydoor': 0}, {'pointDown': {'x': 4672.0001220703125, 'y': 2331.0}, 'pointUp': {'x': 4672.0001220703125, 'y': 408.0}, 'weight': 0.912015974521637, 'detect_bottom': 1, 'detect_door': 0, 'balconydoor': 0}]] }"
json_txt = json_txt.replace('\'', '"')
json.loads(json_txt)
这样就不会有任何错误了!!!
补充:
也可以使用三引号作为外层,双引号直接作为内部的引号,例子如下:
# 下面这两种三引号的写法都是可以的
json_txt = '''{"doors": [[{"pointDown": {"x": 3307.0001220703125, "y": 2367.75}, "pointUp": {"x": 3307.0001220703125, "y": 408.0}, "weight": 0.912015974521637, "detect_bottom": 1, "detect_door": 0, "balconydoor": 0}, {"pointDown": {"x": 4672.0001220703125, "y": 2331.0}, "pointUp": {"x": 4672.0001220703125, "y": 408.0}, "weight": 0.912015974521637, "detect_bottom": 1, "detect_door": 0, "balconydoor": 0}]] }'''
# json_txt = """{"doors": [[{"pointDown": {"x": 3307.0001220703125, "y": 2367.75}, "pointUp": {"x": 3307.0001220703125, "y": 408.0}, "weight": 0.912015974521637, "detect_bottom": 1, "detect_door": 0, "balconydoor": 0}, {"pointDown": {"x": 4672.0001220703125, "y": 2331.0}, "pointUp": {"x": 4672.0001220703125, "y": 408.0}, "weight": 0.912015974521637, "detect_bottom": 1, "detect_door": 0, "balconydoor": 0}]] }"""
json.loads(json_txt)