使用 JQ 解析 json 输出 - 搜索模式

问题描述 投票:0回答:2

我有以下json(基于ndpi输出)

{"src_ip":"x.x.x.x","dest_ip":"x1.x1.x1.x1","src_port":48318,"dst_port":443,"ip":4,"proto":"TCP","ndpi": {"flow_risk": {"35": {"risk":"Susp Entropy","severity":"Medium","risk_score": {"total":210,"client":165,"server":45}}},"confidence": {"1":"Match by port"},"proto":"TLS","proto_id":"91","proto_by_ip":"Unknown","proto_by_ip_id":0,"encrypted":1,"breed":"Safe","category_id":5,"category":"Web"},"detection_completed":1,"check_extra_packets":0,"flow_id":0,"first_seen":1733074272.824,"last_seen":1733074282.757,"duration":9.933,"vlan_id":0,"bidirectional":1,"xfer": {"data_ratio":-0.958,"data_ratio_str":"Download","src2dst_packets":1268,"src2dst_bytes":86239,"src2dst_goodput_bytes":2551,"dst2src_packets":2693,"dst2src_bytes":4042956,"dst2src_goodput_bytes":3865218},"iat": {"flow_min":1,"flow_avg":6.1,"flow_max":4005,"flow_stddev":108.3,"c_to_s_min":0,"c_to_s_avg":7.4,"c_to_s_max":4005,"c_to_s_stddev":137.8,"s_to_c_min":0,"s_to_c_avg":1.4,"s_to_c_max":35,"s_to_c_stddev":2.2},"pktlen": {"c_to_s_min":66,"c_to_s_avg":68.0,"c_to_s_max":514,"c_to_s_stddev":28.8,"s_to_c_min":66,"s_to_c_avg":1501.3,"s_to_c_max":1506,"s_to_c_stddev":76.6},"tcp_flags": {"cwr_count":0,"ece_count":0,"urg_count":0,"ack_count":3961,"psh_count":1323,"rst_count":0,"syn_count":0,"fin_count":0,"src2dst_cwr_count":0,"src2dst_ece_count":0,"src2dst_urg_count":0,"src2dst_ack_count":1268,"src2dst_psh_count":7,"src2dst_rst_count":0,"src2dst_syn_count":0,"src2dst_fin_count":0,"dst2src_cwr_count":0,"dst2src_ece_count":0,"dst2src_urg_count":0,"dst2src_ack_count":2693,"dst2src_psh_count":1316,"dst2src_rst_count":0,"dst2src_syn_count":0,"dst2src_fin_count":0},"c_to_s_init_win":0,"s_to_c_init_win":0}

我可以获得几乎所有信息(src_ip、端口等),但有一个与“flow_risk”相关的信息 {"flow_risk": {"35": {"risk":"暂停熵","severity":"中"

与数量相关(在本例中为 35)。这个数字可以不同(从 01 到 50),我不知道如何过滤以搜索不同的数字。

现在,这是我正在使用的过滤器

cat data.json | jq -r '"\(.src_ip),\(.src_port),\(.dest_ip),\(.dst_port),\(.proto),\(.ndpi.proto),\(.ndpi.category),\(.ndpi.hostname),\(.duration),\(.vlan_id),\(.xfer.src2dst_bytes),\(.xfer.dst2src_bytes),\(.ndpi.flow_risk."35".risk),\(.ndpi.flow_risk."35".severity)"')

当数字正好是 35 时,这有效,但是有没有办法在 jq 中使用通配符之类的东西?我的意思是我怎样才能接受多个号码? (例如:从 01 到 50 搜索?)

类似的东西 (.ndpi.flow_risk."".risk),(.ndpi.flow_risk."".severity)"')

谢谢!

jq ndpi
2个回答
0
投票

过滤器的这一部分可以用多种方式表示,但根据我的经验,使用对象的键的更简单方法之一涉及

to_entries

作为示例,您可以使用类似

.ndpi.flow_risk | to_entries[] | select(.key | tonumber | . <= 50 and . >= 0).value | "\(.risk),\(.severity)"
的方法来获取最后两条信息(如果
"flow risk"
对象保证只有一个键)


0
投票

要访问已知键的变量,请使用

--arg
flag 将变量绑定到值,然后使用
.[$varname]
访问字段:

jq -r --arg n "35" '… .ndpi.flow_risk[$n].risk …'

是否有任何机会可以在 jq 中使用通配符之类的东西?

要访问所有按键,只需使用

.[]
。但是,您可能希望在示例中两次使用
35
时引用相同的键。为此,在创建输出字符串(的相关部分)之前进行迭代,并引用迭代值(上下文):

jq -r '… ,\(.ndpi.flow_risk[] | "\(.risk),\(.severity)")'
© www.soinside.com 2019 - 2024. All rights reserved.