如何构造JMESPath查询路径以提取指定_instrumentIdScheme对应的#value值
解决JMESPath提取指定字段值方案
核心查询语句
你可以使用如下JMESPath表达式完成查询:[*]."m:assetPricing"[*]."m:instrumentId"[? _instrumentIdScheme == 'mhi:MHILIST']."#value"
如果需要直接获取字符串形式的结果,可增加展平操作:[*]."m:assetPricing"[*]."m:instrumentId"[? _instrumentIdScheme == 'mhi:MHILIST']."#value" | [] | [0]
语法说明
- 带特殊符号(冒号、#)的键名必须用双引号包裹,否则JMESPath会识别为语法错误
[? 条件]是JMESPath的过滤表达式,用于筛选符合指定条件的数组元素- 末尾的
| []用于把多层嵌套的数组合并为一层,[0]用于取出第一个匹配到的结果值
Python调用示例
import jmespath # 你已转换完成的JSON数据 target_data = [ { "_fpmlVersion": "5-6", "header": { "messageType": "PrevDayCloseBond", "sendTo": [ { "#value": "Anvil" } ], "creationTimestamp": "2021-09-28T06:00:00.000Z" }, "m:asOfDate": { "#value": "2021-09-28T00:00:00.000Z" }, "_xmlns": "http://www.fpml.org/FpML-5/reporting", "_xmlns:m": "urn:com.mizuho.bdm", "_xmlns:mhi": "urn:com.mizuho.bdm.mhi", "_xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance", "_xsi:schemaLocation": "http://www.fpml.org/FpML-5/reporting http://svc-bdmentity01p:8080/schema/7.2.0/com/mizuho/bdm/fpml/fpml-5-6-reporting.xsd urn:com.mizuho.bdm http://svc-bdmentity01p:8080/schema/7.2.0/com/mizuho/bdm/fpml/mizuho-fpml.xsd urn:com.mizuho.bdm.mhi http://svc-bdmentity01p:8080/schema/7.2.0/com/mizuho/bdm/mhi/fpml/mhi-fpml.xsd", "m:assetPricing": [ { "m:pricingSource": [ { "#value": "LON-XEN-BBG" }, { "#value": "BGN", "_pricingSourceScheme": "mizuho:bloomberg-source" } ], "m:instrumentId": [ { "#value": "100001380992", "_instrumentIdScheme": "mhi:MHILIST" }, { "#value": "100001380992", "_instrumentIdScheme": "mhsa:instrument-id" } ], "m:currency": { "#value": "USD" }, "m:price": [ { "value": 140.78125, "measureType": { "#value": "Bid Price", "_assetMeasureScheme": "mizuho:price-type" } }, { "value": 140.875, "measureType": { "#value": "Mid Price", "_assetMeasureScheme": "mizuho:price-type" } }, { "value": 140.96875, "measureType": { "#value": "Offer Price", "_assetMeasureScheme": "mizuho:price-type" } } ] } ], "m:pricingDate": "2021-09-28T00:00:00.000Z" } ] # 执行查询 query_exp = '[*]."m:assetPricing"[*]."m:instrumentId"[?_instrumentIdScheme == \'mhi:MHILIST\']."#value" | [] | [0]' result = jmespath.search(query_exp, target_data) print(result) # 输出结果:100001380992
内容的提问来源于stack exchange,提问作者Bruno Lorena
相关产品推荐
相关产品推荐

