jq:获得两个级别的密钥

Hen*_*ica 10 jq

我有一些看起来像这样的json数据:

{
  "p": {
    "d": {
      "a" : {
        "r": "foo",
        "g": 1
      },
      "b": {
        "r": "bar",
        "g": 2
      }
    },
    "c": {
      "e": {
        "r": "baz",
        "g": 1
      }
    },
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

我想要的东西:

{
  "d": [ 
    "a",
    "b"
  ],
  "c": [
    "e"
  ]
}
Run Code Online (Sandbox Code Playgroud)

我可以在第一级"p"下获取键列表,jq '.p|keys'在第二级使用结构和键jq '.p|map(.|keys)',但我无法弄清楚如何组合它.

jas*_*ard 14

一般来说

顶级按键:

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

[
  "categories",
  "crate",
  "keywords",
  "versions"
]
Run Code Online (Sandbox Code Playgroud)

两级按键:

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": []
}
Run Code Online (Sandbox Code Playgroud)

方法版本

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
}
Run Code Online (Sandbox Code Playgroud)


小智 13

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

jq '.p | map_values(keys)'
Run Code Online (Sandbox Code Playgroud)

在低于1.5的jq版本上,map_values未定义:相反,您可以使用[]|=:

jq '.p | . []|= keys'
Run Code Online (Sandbox Code Playgroud)

  • 试试`jq'.p | .[] | = keys'` (2认同)