简体   繁体   English

以下是有效的json吗? 我如何将它转换为python中的dict

[英]is the following a valid json ? how do I convert it into a dict in python

Is the following a valid JSON : 以下是有效的JSON:

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

json validator sites ( https://jsonlint.com/ ) says it it isn't. json验证站点( https://jsonlint.com/ )说它不是。 How can I make this a valid json ? 我怎样才能使它成为有效的json? converting this to a dict in python truncates blocks of json (the "AGENT" part). 将其转换为python中的dict会截断json的块(“AGENT”部分)。 How can I convert this block to a dict in python without losing json blocks ? 如何在不丢失json块的情况下将此块转换为python中的dict? This is JSON returned from a GET request. 这是从GET请求返回的JSON。 Using the following does not work 使用以下功能不起作用

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

You just need to make it one JSON object by adding braces: 您只需要通过添加大括号使其成为一个JSON对象:

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

Now it is valid: 现在它是有效的:

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': []}}

Speaking on parsing http response - you can make things simple: 谈到解析http响应 - 你可以简单地说:

item_dict = requests.get(<url>).json()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM