python - 如果嵌套 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 / 字典可用格式(需要单引号的键)的最有效方法是什么?
解决方案
receivedJson['Data']
可能被错误地倾倒了两次。您始终可以在解析之前检查值类型。要检查该值是否是转储的 JSON,您可以首先使用这样的函数。
def is_json(json_):
try:
json.loads(json_)
return True
except Exception as e:
return False
推荐阅读
- laravel-5 - 在 laravel 中使用 typeahead 进行 JQuery 自动完成搜索
- vue.js - 将 var 传递给 meta 中的 vue 路由器
- django - django celery AsyncResult AttributeError: 'DisabledBackend' 对象没有属性 '_get_task_meta_for'
- java - 无法在 Eclipse 中导出到存档文件“访问被拒绝”
- ansible - 稳定 | 错误!任务中未检测到任何操作。这通常表示模块名称拼写错误或模块路径不正确
- cytoscape.js - 方向感知邻里
- java - 如何在 Java 中处理一维数组的跳过输入
- arrays - For 循环中的 If 语句
- c# - 在 C# 中动态更改配置设置 kafka
- powerbi - 如何创建一个执行条件的度量,以及 groupby 和按结果计算该组的计数(DAX/PowerBI)