簡體   English   中英

以下是有效的json嗎? 我如何將它轉換為python中的dict

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

以下是有效的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

您只需要通過添加大括號使其成為一個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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM