在jq中使用多个通配符选择JSON文件中的对象

在jq中使用多个通配符选择JSON文件中的对象

我有一个 JSON 文件,其中包含以下结构中逐行的数千条记录,具有不同的值。

例子:

{"in": 5,"li": [{"st": 1508584161,"abc": 128416626,"ta": 33888}],"usr": {"is": "222108923573880","ie": "222108923573880"},"st2": 1508584161,"ei": {"ev": 0,"rt": 10},"rn": 947794,"st1": 1508584161}
{"in": 5,"li": [{"st": 1508584174,"abc": 128572802,"ta": 33504}],"usr": {"is": "222108923573880","ie": "222108923573880"},"st2": 1508584174,"ei": {"ev": 0,"rt": 19},"rn": 947795,"st1": 0}
{"in": 5,"li": [{"st": 1508584145,"abc": 279682,"ta": 50000}],"usr": {"is": "222108923573880","ie": "222108923573880"},"st2": 1508584145,"ei": {"ev": 0,"rt": 18},"rn": 947796,"st1": 1508584145}
{"in": 5,"li": [{"st": 1508584183,"abc": 1378680,"ta": 49840}],"usr": {"is": "222108923573880","ie": "222108923573880"},"st2": 1508584183,"ei": {"ev": 0,"rt": 10},"rn": 947797,"st1": 1508584186}
{"nt": 4}

我试图在 JSON 文件中选择符合以下条件的对象(记录)并输出到另一个文件。

st1 是 < 或 = st2

st1 不为 0

st2 不为 0

st1 小于 2147483647

st2 小于 2147483647

在输出中,原始文件的页脚 ({"nt": 4}) 也应该位于输出文件中,因此可以使用新记录数进行编辑

输出文件示例:

{"in": 5,"li": [{"st": 1508584161,"abc": 128416626,"ta": 33888}],"usr": {"is": "222108923573880","ie": "222108923573880"},"st2": 1508584161,"ei": {"ev": 0,"rt": 10},"rn": 947794,"st1": 1508584161} 
{"nt": 1}

我有以下内容:

jq -c 'select((.st1 > 0 and .st2 > 0 and .st1 < .st2) or (.st1 < 214748647 and .st2 < 214748647 and .st1 > 0 and .st2 > 0 and .st1 < .st2)) file.json

我尝试了各种排列,但它没有捕获正确的记录。

答案1

使用正确的数字,可以直接翻译您的条件:

$ jq -c 'select(.st1 <= .st2 and 
                .st1 > 0 and .st2 > 0 and 
                .st1 < 2147483647 and .st2 < 2147483647)' file.json 
{"in":5,"li":[{"st":1508584161,"abc":128416626,"ta":33888}],"usr":{"is":"222108923573880","ie":"222108923573880"},"st2":1508584161,"ei":{"ev":0,"rt":10},"rn":947794,"st1":1508584161}
{"in":5,"li":[{"st":1508584145,"abc":279682,"ta":50000}],"usr":{"is":"222108923573880","ie":"222108923573880"},"st2":1508584145,"ei":{"ev":0,"rt":18},"rn":947796,"st1":1508584145}

请注意右括号',并且没有双括号。我不明白为什么你将条件分成两个and由 相连的子句or,这不是你的条件所说的。

无论如何,这捕获了正确的记录;现在我们只需要添加页脚。最简单的方法是执行一个额外的步骤,为了简洁起见,缩短上面的 select 子句:

jq -c 'select ...' file.json > out.json
printf '{"nt":%i}\n' `wc -l < out.json` >> out.json 

我想也可以用复杂的表达来做到这一点jq,但我没有尝试过。

相关内容