【问题标题】:is the following a valid json ? how do I convert it into a dict in python以下是有效的 json 吗?如何在python中将其转换为dict
【发布时间】:2018-12-13 21:14:48
【问题描述】:

以下是有效的 JSON 吗:

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

json 验证器站点 (https://jsonlint.com/) 说它不是。我怎样才能使它成为一个有效的 json ?将其转换为 python 中的 dict 会截断 json 块(“代理”部分)。如何在不丢失 json 块的情况下将此块转换为 python 中的字典?这是从 GET 请求返回的 JSON。使用以下不起作用

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

【问题讨论】:

    标签: python json rest


    【解决方案1】:

    您只需通过添加大括号使其成为一个 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()
    

    【讨论】:

      猜你喜欢
      • 2019-10-08
      • 1970-01-01
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 2015-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多