首页 > 解决方案 > 如果嵌套 3 层或更深,Json 加载函数无法转换为字典

问题描述

我正在接收在正文请求中发送到 Python / Django 应用程序的 json 值,如下所示:

127.0.0.1:8000/devices/1/?json={ "DeviceId":"1-9024-9929", "Date":"1/4/2019 9:52:2", "Location":"-1.000000000,-1.000000000", "Key":"{XXXXX-XXXX-XXXX-XXXX-XXXXX}", "Data":"{\"Value0\":\"{ \"ReferenceValue\":\"Elevation\", \"Prediction\":18.297534944, \"ModelPredictionFit\":3.196141712e-2, \"PCBasedEstimatedError\":3.196141712e-2, \"PCScore\":4.855016704, \"PredictionValueScore\":4.687027008e-2}\",}"}

当收到服务器端时,我使用 json.loads 转换为

{'DeviceId': '1-9024-9929', 'Date': '1/4/2019 9:52:2', 'Location': '-1.000000000,-1.000000000', 'Key': '{XXXXX-XXXX-XXXX-XXXX-XXXXX}', 'Data': '{"Value0":"{ "ReferenceValue":"Elevation", "Prediction":18.297534944, "ModelPredictionFit":3.196141712e-2, "PCBasedEstimatedError":3.196141712e-2, "PCScore":4.855016704, "PredictionValueScore":4.687027008e-2}",}'}

虽然我可以通过适当的键访问任何值,例如

receivedJson["DeviceId"]

> 1-9024-9929

'Data' 键不能用于访问子项,因为它的格式不正确:

recievedJson["Data"]

> {"Value0":"{ "ReferenceValue":"Elevation", "Prediction":18.297534944, "ModelPredictionFit":3.196141712e-2, "PCBasedEstimatedError":3.196141712e-2, "PCScore":4.855016704, "PredictionValueScore":4.687027008e-2}",}

将此嵌套数组转换回 json / 字典可用格式(需要单引号的键)的最有效方法是什么?

标签: pythonjsondictionarynested

解决方案


receivedJson['Data']可能被错误地倾倒了两次。您始终可以在解析之前检查值类型。要检查该值是否是转储的 JSON,您可以首先使用这样的函数。

def is_json(json_):
   try:
      json.loads(json_)
      return True
   except Exception as e:
      return False

推荐阅读