简体   繁体   English

使用jq列出JSON对象中的键

[英]Using jq to list keys in a JSON object

I have a hierarchically deep JSON object created by a scientific instrument, so the file is somewhat large (1.3MB) and not readily readable by people. 我有一个由科学仪器创建的分层深度JSON对象,因此文件有点大(1.3MB)并且人们不易读取。 I would like to get a list of keys, up to a certain depth, for the JSON object. 我想获得一个JSON对象的密钥列表,直到某个深度。 For example, given an input object like this 例如,给定一个像这样的输入对象

{
    "acquisition_parameters": {
        "laser": {
            "wavelength": {
                "value": 632,
                "units": "nm"
            }
        },
        "date": "02/03/2525",
        "camera": {}
    },
    "software": {
        "repo": "github.com/username/repo",
        "commit": "a7642f",
        "branch": "develop"
    },
    "data": [{},{},{}]
}

I would like an output like such. 我想要这样的输出。

{
    "acquisition_parameters": [
        "laser",
        "date",
        "camera"
    ],
    "software": [
        "repo",
        "commit",
        "branch"
    ]
}

This is mainly for the purpose of being able to enumerate what is in a JSON object. 这主要是为了能够枚举JSON对象中的内容。 After processing the JSON objects from the instrument begin to diverge: for example, some may have a field like .frame.cross_section.stats.fwhm , while others may have .sample.species , so it would be convenient to be able to interrogate the JSON object on the command line. 处理后,仪器中的JSON对象开始发散:例如,有些可能有.frame.cross_section.stats.fwhm这样的字段,而其他可能有.sample.species ,因此可以方便地查询命令行上的JSON对象。

The following should do exactly what you want 以下应该完全符合您的要求

jq '[(keys - ["data"])[] as $key | { ($key): .[$key] | keys }] | add'

This will give the following output, using the input you described above: 这将使用您上面描述的输入提供以下输出:

{
  "acquisition_parameters": [
    "camera",
    "date",
    "laser"
  ],
  "software": [
    "branch",
    "commit",
    "repo"
  ]
}

Given your purpose you might have an easier time using the paths builtin to list all the paths in the input and then truncate at the desired depth: 根据您的目的,您可以更轻松地使用内置paths列出输入中的所有路径,然后在所需深度处截断:

$  echo '{"a":{"b":{"c":{"d":true}}}}' | jq -c '[paths|.[0:2]]|unique'
[["a"],["a","b"]]

Here is another variation uing reduce and setpath which assumes you have a specific set of top-level keys you want to examine: 这是另一个变量uing reducesetpath ,它假设您有一组要检查的特定顶级键:

  . as $v
| reduce ("acquisition_parameters", "software") as $k (
     {}; setpath([$k]; $v[$k] | keys)
  )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM