在不知道密钥的情况下打印第一个值

Print the first value without knowing the key

我有一个 JSON 值

{
    "RandomKey1": "3.1.44.0",
    "Common": {
        "Services": "3.50.103.0",
        "Common": "3.50.103.0"
    }
}

我想获取RandomKey1的值。您可能已经猜到了,每次加载页面时键的名称都会发生变化,因此我需要获取第 0 个键的值。保证在第0位

我期待至少有一些结果

cat result.json | jq -r '.[0]'

但我得到了错误

jq: error (at <stdin>:0): Cannot index object with number. 

我尝试了 keys 功能,它按预期 return 按键。但是没有 values 函数,否则我可以获得值并且 return 只有第一个元素

cat result.json | jq -r 'keys'

当键名未知时,有没有办法从这个字符串中获取第 0 个值?

您可以使用 to_entries 功能到达那里!

jq 'to_entries|.[0].value' file.json

应该可以解决问题。

来自 jq 文档:

If to_entries is passed an object, then for each k: v entry in the input, the output array includes {"key": k, "value": v}.

所以在它之后你的 json 将如下所示:

[
  {
    "key": "RandomKey1",
    "value": "3.1.44.0"
  },
  {
    "key": "Common",
    "value": {
      "Services": "3.50.103.0",
      "Common": "3.50.103.0"
    }
  }
]

在哪里可以找到第一个键及其对应的值。

您正在寻找 first/1

first(.[])

Online demo

如果您至少知道第一个值始终是标量,那么您可以丢弃其余输入以避免耗尽内存和浪费 CPU 时间。

$ jq --stream -n 'input[1]' file
"3.1.44.0"

I tried the function keys

您可以像这样使用 keys_unsorted 函数:

.[keys_unsorted[0]]