如何在jq --stream命令中使用select筛选指定JSON对象?
问题
我有一个约100GB的超大JSON文档(example.json),需要用jq工具解析出符合特定条件的对象。由于文件过大无法加载至内存,必须使用--stream选项。我已经掌握非流式场景下的筛选方法:
jq '.in_network[] | select(.billing_code == "99285")' example.json
目标是提取billing_code等于99285的in_network对象,求带--stream选项的jq命令实现该需求。
示例JSON结构
{ "reporting_entity_name" : "INSURANCE COMPANY", "reporting_entity_type" : "INSURER", "last_updated_on" : "2022-12-01", "version" : "1.0.0", "in_network" : [ { "negotiation_arrangement" : "ffs", "name" : "ER VISIT", "billing_code_type" : "CPT", "billing_code_type_version" : "2022", "billing_code" : "99285", "description" : "HIGHEST LEVEL ER VISIT", "negotiated_rates" : [ { "provider_groups" : [ { "npi" : [ 111111111, 222222222], "tin" : { "type" : "ein", "value" : "99-9999999" } } ], "negotiated_prices" : [ { "negotiated_type" : "negotiated", "negotiated_rate" : 550.50, "expiration_date" : "9999-12-31", "service_code" : [ "23" ], "billing_class" : "institutional" } ] } ] } ] }
解决方案
使用jq的流式处理模式,需要跟踪in_network数组中的对象,当检测到某个对象的billing_code为99285时,完整重建该对象并输出。对应的命令如下:
jq --stream ' select(.[0][0] == "in_network") | .[0] |= (.[1:] | if .[0] | tonumber? then . else [] end) | reduce . as $item ({}; if $item[0] == [] then if .current.billing_code == "99285" then .current else empty end else setpath($item[0]; $item[1]) | if $item[0][-1] == "billing_code" then .current = getpath($item[0][0:-1]) else . end end ) ' example.json
命令说明
select(.[0][0] == "in_network"):只处理in_network路径下的流式数据,过滤掉其他无关字段,减少处理量。.[0] |= (.[1:] | if .[0] | tonumber? then . else [] end):调整路径格式,去掉顶层的"in_network",保留数组索引和后续字段路径。reduce块:逐个处理流式数据条目,动态构建当前in_network对象:- 当遇到数组结束标记(
.[0] == [])时,检查已构建的current对象的billing_code是否符合条件,符合则输出该对象。 - 否则,用
setpath将当前数据条目写入对应路径;如果当前处理的是billing_code字段,则将其所在的整个对象保存到current变量中。
- 当遇到数组结束标记(
预期输出
{ "negotiation_arrangement": "ffs", "name": "ER VISIT", "billing_code_type": "CPT", "billing_code_type_version": "2022", "billing_code": "99285", "description": "HIGHEST LEVEL ER VISIT", "negotiated_rates": [ { "provider_groups": [ { "npi": [ 111111111, 222222222 ], "tin": { "type": "ein", "value": "99-9999999" } } ], "negotiated_prices": [ { "negotiated_type": "negotiated", "negotiated_rate": 550.5, "expiration_date": "9999-12-31", "service_code": [ "23" ], "billing_class": "institutional" } ] } ] }
内容的提问来源于stack exchange,提问作者kostr
相关产品推荐
相关产品推荐

