jq:获取两级密钥

问题描述 投票:0回答:3

我有一些 json 数据,如下所示:

{
  "p": {
    "d": {
      "a" : {
        "r": "foo",
        "g": 1
      },
      "b": {
        "r": "bar",
        "g": 2
      }
    },
    "c": {
      "e": {
        "r": "baz",
        "g": 1
      }
    },
    ...
  }
}

我想要类似的东西:

{
  "d": [ 
    "a",
    "b"
  ],
  "c": [
    "e"
  ]
}

我可以使用

jq '.p|keys'
获取“p”下第一层的键列表,使用
jq '.p|map(.|keys)'
获取第二层的结构和键,但我不知道如何组合它。

jq
3个回答
27
投票

使用

map_values
而不是
map
来映射 JSON 对象的值,同时保留键:

jq '.p | map_values(keys)'

在低于 1.5 的 jq 版本上,未定义

map_values
:相反,您可以使用
[]|=
:

jq '.p | . []|= keys'

14
投票

一般情况

顶级按键:

curl -s https://crates.io/api/v1/crates/atty | jq '. |= keys'

[
  "categories",
  "crate",
  "keywords",
  "versions"
]

两级按键:

curl -s https://crates.io/api/v1/crates/atty | jq '.| map_values(keys)'

{
  "crate": [
    "badges",
    "categories",
    "created_at",
    "description",
    "documentation",
    "downloads",
    "exact_match",
    "homepage",
    "id",
    "keywords",
    "links",
    "max_version",
    "name",
    "newest_version",
    "recent_downloads",
    "repository",
    "updated_at",
    "versions"
  ],
  "versions": [
    0,
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    10,
    11,
    12,
    13,
    14,
    15,
    16
  ],
  "keywords": [
    0,
    1,
    2
  ],
  "categories": []
}

方法版本

topLevelJsonKeys() {
 curl -s $1 | jq '. |= keys'
  # EXAMPLE: 
  # topLevelJsonKeys https://crates.io/api/v1/crates/atty
}

topLevelJsonKeys2() {
  curl -s $1 | jq '.| map_values(keys)'
  # EXAMPLE: 
  # topLevelJsonKeys2 https://crates.io/api/v1/crates/atty
}

2
投票

这是一个使用 reducesetpath

的解决方案
  .p
| reduce keys[] as $k (
     .
   ; setpath([$k]; .[$k] | keys)
)
© www.soinside.com 2019 - 2024. All rights reserved.