简体   繁体   中英

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

Is the following a valid JSON :

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

json validator sites ( https://jsonlint.com/ ) says it it isn't. How can I make this a valid json ? converting this to a dict in python truncates blocks of json (the "AGENT" part). How can I convert this block to a dict in python without losing json blocks ? This is JSON returned from a GET request. 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:

{
 "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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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