Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-JSON格式无效-如何解析_Python_Python 2.7 - Fatal编程技术网

Python-JSON格式无效-如何解析

Python-JSON格式无效-如何解析,python,python-2.7,Python,Python 2.7,我正在获取以下JSON格式的数据: { address:[ "test1" ], city:"test2", country:"test3", postal_code:"test4", state:"test5" } 当我试图通过以下方式解析它时: json.loads(data) 我收到一个错误:属性名应包含在双引号中 有没有办法用python解析它 提前感谢,您的变量应该像“地址”或“城市” 不用说,更好的解决方案是在源位置修复损坏的数据。但是如果你不能做

我正在获取以下JSON格式的数据:

{
  address:[
    "test1"
  ],
  city:"test2",
  country:"test3",
  postal_code:"test4",
  state:"test5"
}
当我试图通过以下方式解析它时:

json.loads(data)
我收到一个错误:属性名应包含在双引号中

有没有办法用python解析它


提前感谢,

您的变量应该像“地址”或“城市”


不用说,更好的解决方案是在源位置修复损坏的数据。但是如果你不能做到这一点,你可以尝试用一个简单的正则表达式来解决这个问题。简单,如“如果你向它扔任何更复杂的东西,它就会失败”,但作为一个快速而肮脏的解决方案,可能已经足够了:

import re
import json
with open("almost.json") as infile:
    jstring = infile.read()
data = json.loads(re.sub(r"(\w+):", r'"\1":', jstring))

json标准需要带有
”的密钥,因此无法使用json模块解码数据。 但是,您可以使用
demjson
(pip-install-damson)来完成

demjson.decode(数据)


地址、城市和其他字段缺少双引号。这个答案很有效。我使用
demjson
解析任何产生JSON.JSONDECODEROR的JSON,使用普通解码器。
import re
import json
with open("almost.json") as infile:
    jstring = infile.read()
data = json.loads(re.sub(r"(\w+):", r'"\1":', jstring))