使用 jq returns "Cannot index array with string" 从 JSON 中的数组中提取元素

Extracting element from array in JSON with jq returns "Cannot index array with string"

我有一个 JSON 文件:

$ cat ~/tmp/example1.json
[
  {
    "keyProp": 11111111111111,
    "values": [
      "VALUE1"
    ]
  },
  {
    "keyProp": 2222,
    "values": [
      "VALUE2"
    ]
  }
]

我想将 jq 用于 select 值,其中 keyProp==11111111111111。预期输出为 'VALUE2'

我试过但没有结果:

cat ~/tmp/example1.json | jq 'select(.keyProp==11111111111111)'
jq: error (at <stdin>:14): Cannot index array with string "keyProp"

到select一个块你需要使用文档中描述的表达式:

select(boolean_expression)

The function select(foo) produces its input unchanged if foo returns true for that input, and produces no output otherwise.

It’s useful for filtering lists: [1,2,3] | map(select(. >= 2)) will give you [2,3].

jq '.[] | select(.id == "second")'
 Input  [{"id": "first", "val": 1}, {"id": "second", "val": 2}]
 Output {"id": "second", "val": 2}

所以在这种情况下你需要说:

$ jq '.[] | select(.keyProp==11111111111111)' file
{
  "values": [
    "VALUE1"
  ],
  "keyProp": 11111111111111
}

要提取value中的列表,就这么说:

$ jq '.[] | select(.keyProp==11111111111111).values' file
[
  "VALUE1"
]

您甚至可以使用索引提取第一个值:

$ jq '.[] | select(.keyProp==11111111111111).values[0]' file
"VALUE1"