使用多个条件过滤对象,包括比较两个对象字段

时间:2018-06-13 18:07:38

标签: syntax jq

有一个JSON对象列表,我试图根据最小值检查和两个字段之间的比较来过滤它们。

{
  "preview": false,
  "init_offset": 0,
  "messages": [],
  "fields": [
    {
      "name": "A"
    },
    {
      "name": "B"
    },
    {
      "name": "Diff"
    },
    {
      "name": "Threshold"
    }
  ],
  "results": [
    {
      "A": "foo",
      "B": "bar",
      "Diff": "1095",
      "Threshold": "1200"
    },
    {
      "A": "baz",
      "B": "bux",
      "Diff": "81793",
      "Threshold": "0"
    },
    {
      "A": "quux",
      "B": "quuz",
      "Diff": "194"
    },
    {
      "A": "moo",
      "B": "goo",
      "Diff": "5000",
      "Threshold": "2000"
    }
 ]
}

我最近来的是

.results
| map(.Threshold //= "0")
| .[]
| select((.Threshold|tonumber > 0) and 
         (.Diff|tonumber > .Threshold|tonumber))

但是这给了

Cannot index string with string "Threshold"

错误。

基本上我想返回Diff大于非零阈值的所有结果。所以在这种情况下:

{
  "A": "moo",
  "B": "goo",
  "Diff": "5000",
  "Threshold": "2000"
}

使用jq 1.5 FWIW。

1 个答案:

答案 0 :(得分:1)

你只是错过了一些括号。比较:

select((.Threshold|tonumber) > 0 and
       (.Diff|tonumber) > (.Threshold|tonumber))

或避免双重转换:

select( (.Threshold|tonumber) as $t
        | $t > 0 and (.Diff|tonumber) > $t )

您还可以稍微简化整个程序:

.results[]
| select( ((.Threshold // 0) | tonumber) as $t 
          | $t > 0 and (.Diff|tonumber) > $t )