我有以下json数据:
{"jsonrpc":"2.0","result":[],"id":1}
{"jsonrpc":"2.0","result":[{"hostmacroid":"2392","hostid":"10953","macro":"{$GATEWAY}","value":"10.25.230.1"}],"id":1}
{"jsonrpc":"2.0","result":[{"hostmacroid":"1893","hostid":"12093","macro":"{$GATEWAY}","value":"10.38.118.1"}],"id":1}
{"jsonrpc":"2.0","result":[{"hostmacroid":"2400","hostid":"14471","macro":"{$GATEWAY}","value":"10.25.230.1"}],"id":1}
{"jsonrpc":"2.0","result":[{"hostmacroid":"799","hostid":"10798","macro":"{$GATEWAY}","value":"10.36.136.1"}],"id":1}
{"jsonrpc":"2.0","result":[],"id":1}
{"jsonrpc":"2.0","result":[{"hostmacroid":"1433","hostid":"10857","macro":"{$GATEWAY}","value":"10.38.24.129"}],"id":1}
{"jsonrpc":"2.0","result":[{"hostmacroid":"842","hostid":"13159","macro":"{$GATEWAY}","value":"10.38.113.1"}],"id":1}
{"jsonrpc":"2.0","result":[],"id":1}
我试图提取&#34;值的价值&#34;每一行的字段。 jq -r '.result[].value' <jsonfile>
完美无缺,但没有考虑到没有&#34;值&#34;的JSON行。领域。我希望它为他们打印一个空行。这有可能与jq?
答案 0 :(得分:1)
这样可行:
jq -r '.result | if length > 0 then .[0].value else "" end'
答案 1 :(得分:1)
您可以使用:
jq -r '.result[].value // "" ' a.json
这使用或运算符//
。如果存在.result[].value
,则会打印该值,否则会打印一个空行。
答案 2 :(得分:1)
由于false // X
和null // X
生成X,.result[].value // ""
可能不是您想要的所有情况。
为了达到我所理解的目标,您可以使用以下过滤器:
.result[] | if has("value") then .value else "" end