如何将JSONPath表达式$.activations[0].bidReference转为Python代码?
问题与解决方法
问题
找到有效JSONPath表达式$.activations[0].bidReference可提取目标值,但转换为Python代码时写成:
jdata = response.json() bidreference = jdata["activations[0].bidReference"]
运行时触发KeyError。对应的JSON响应结构如下:
{ "orderReference": "88a13d98-f9c9-49cb-8682-2ec2ef27bc73", "requestReference": "106d1b23-978a-4894-a1e1-e3de2b0c0f02", "createdUtc": "2024-08-06T12:22:30+00:00", "receivedUtc": "0001-01-01T00:00:00+00:00", "startUtc": "2024-08-06T12:30:00+00:00", "endUtc": "2024-08-06T12:45:00+00:00", "numberOfActivations": 1, "activations": [ { "requestReference": "106d1b23-978a-4894-a1e1-e3de2b0c0f02", "orderReference": "88a13d98-f9c9-49cb-8682-2ec2ef27bc73", "bidReference": "e810ff33-4946-425d-9c63-1584125efc9b", "status": "Activated", "direction": "UP", "startUtc": "2024-08-06T12:30:00+00:00", "endUtc": "2024-08-06T12:45:00+00:00", "quantity": 15, "reasonCode": null, "reasonText": null, "powerPlantName": "Nore 1", "powerPlantId": 7303, "priceAreaId": 1, "regionId": 10 } ], "events": [ { "activationReference": "88a13d98-f9c9-49cb-8682-2ec2ef27bc73", "activationRequestReference": "106d1b23-978a-4894-a1e1-e3de2b0c0f02", "eventType": "AcceptedAcknowledgeOut", "eventMessage": "Activation request from TSO was acknowledged", "eventUtc": "2024-08-06T12:22:32.604432+00:00" }, { "activationReference": "88a13d98-f9c9-49cb-8682-2ec2ef27bc73", "activationRequestReference": "106d1b23-978a-4894-a1e1-e3de2b0c0f02", "eventType": "AcceptedOut", "eventMessage": "1 accepted and 0 rejected activations sent to TSO", "eventUtc": "2024-08-06T12:22:32.832895+00:00" }, { "activationReference": "88a13d98-f9c9-49cb-8682-2ec2ef27bc73", "activationRequestReference": "106d1b23-978a-4894-a1e1-e3de2b0c0f02", "eventType": "AcceptedAcknowledgeIn", "eventMessage": "TSO accepted acknowledge", "eventUtc": "2024-08-06T12:22:34.387739+00:00" } ], "activationType": "ACTIVATION", "activationRelations": [ { "reference": "e810ff33-4946-425d-9c63-1584125efc9b", "requestReference": "106d1b23-978a-4894-a1e1-e3de2b0c0f02", "powerPlantId": 7303, "powerPlantName": "Nore 1", "priceAreaId": 1, "regionId": 10 } ], "error": false }
错误原因
Python字典不支持直接将完整JSONPath字符串作为键名访问。jdata["activations[0].bidReference"]是在尝试查找一个名为activations[0].bidReference的顶级键,而这个键在JSON结构中不存在,因此触发KeyError。
解决方法
方法1:原生Python逐层访问
按照JSON结构层级,先获取activations列表,再取索引0的元素,最后提取bidReference字段:
jdata = response.json() bidreference = jdata["activations"][0]["bidReference"]
这种方法无需额外依赖,适合结构固定的场景。
方法2:使用JSONPath库
如果需要复用JSONPath表达式,可以使用第三方库(如jsonpath-ng)来解析查询:
- 先安装库:
pip install jsonpath-ng
- 编写代码:
from jsonpath_ng import parse jdata = response.json() # 传入你的JSONPath表达式 jsonpath_expr = parse("$.activations[0].bidReference") # 执行查询 matches = jsonpath_expr.find(jdata) # 提取匹配到的值 bidreference = matches[0].value
这种方法适合复杂路径查询或动态场景。
内容的提问来源于stack exchange,提问作者Magnus Jensen
相关产品推荐
相关产品推荐

