jqselect条件

Jq select condition

我有一个日志文件,想从中grep数据,所以我使用Jq按参数过滤一些数据。

正如我上面所说,我将根据传递给 Jq 的参数过滤数据

详情:

我的日志文件的结构:

 {
    city: "",
    phone_number: "",
    address: "",
    zip_code: "",
    person : {
        name: "",
        sex: "",
        ...
    }
 }

我的预期是我想忽略用于过滤的属性,如果是 emptynull

例如:

cat my_log_file.log | jq -r --arg city ${city} --arg name ${name}  'select(.city == $city and .person.name == $name)'

使用上面的命令,如果我传递的 ${city} 参数是 emptynull 那么我想用 city 删除过滤器并且只需使用 name

进行过滤

我试过了还是不行

... I want to ignore attributes if that is empty or null

要从对象中删除不需要的键,您可以将其传递给过滤器,例如:

with_entries(select(.value | (. != "" and . != {} and . != null)))

要检查一个值,比如 $value,是 null 还是 "",可以这样写:

$value == null or $value == ""

所以你可以通过使用这个 jq 程序来实现你想要的:

def agrees(value): 
  value == null or value == "" or . == value;

select( (.city | agrees($city)) and
        (.person.name | agrees($name)) )