以下是有效的json吗?如何将其转换为python中的字典

时间:2018-07-05 11:40:55

标签: python json rest

以下是有效的JSON:

 "AGENT ": {
    "pending": [],
    "active": null,
    "completed": [{}]
 },
 "MONITORING": {
    "pending": [],
    "active": null,
    "completed": [{}]
 }

json验证者网站(https://jsonlint.com/)表示不是。如何使它成为有效的json?将其转换为python中的dict会截断json块(“ AGENT”部分)。如何在不丢失json块的情况下将此块转换为python中的dict?这是从GET请求返回的JSON。使用以下内容无效

response = requests.get(<url>)
data = response.content
json_data = json.dumps(data)
item_dict = json.loads(data)
item_dict = data

1 个答案:

答案 0 :(得分:3)

您只需通过添加花括号使其成为一个JSON对象:

{
 "AGENT ": {
    "pending": [],
    "active": null,
    "completed": [{}]
 },
 "MONITORING": {
    "pending": [],
    "active": null,
    "completed": [{}]
 }
}

现在有效:

In [27]: json.loads('''{
   ....:  "AGENT ": {
   ....:     "pending": [],
   ....:     "active": null,
   ....:     "completed": [{}]
   ....:  },
   ....:  "MONITORING": {
   ....:     "pending": [],
   ....:     "active": null,
   ....:     "completed": [{}]
   ....:  }
   ....: }''')
Out[27]: 
{u'AGENT ': {u'active': None, u'completed': [{}], u'pending': []},
 u'MONITORING': {u'active': None, u'completed': [{}], u'pending': []}}

谈到解析http响应-您可以使事情变得简单:

item_dict = requests.get(<url>).json()
相关问题