如何使用 jq 获取根密钥和密钥类型

How to get root keys and key types using jq

让我们以这个简单的数据文件为例:http://data.cdc.gov/data.json

我知道如何获取根密钥名称:

jq keys_unsorted[] -r data.json

产生:

@context
@id
@type
conformsTo
describedBy
dataset

而且我知道如何获取密钥类型:

jq 'map(type)' data.json

产生:

[
  "string",
  "string",
  "string",
  "string",
  "string",
  "array"
]

有没有办法将它组合成return对? (我真正想做的是找到第一个根级数组的键名,如果有的话)。我可以写一个例程来解决这个问题,但这似乎不够优雅。

附加问题:如何确定密钥的类型(例如,我会以某种形式将 "dataset" 发送到 jq 并在 return 中得到 "array")?

jq 'first(path(.[] | select(type == "array"))[0])' < data.json

顶级项.[]被过滤掉select(type == "array"),只选择数组类型的项; path() returns .中路径的数组表示,即数组项的键名; first() 提取第一个路径。

因此命令的结果是第一个顶级数组项的键名。

示例输出

"dataset"

How to you determine the type of a key (e.g., I would send "dataset" to jq in some form and would get "array" in return).

你的意思可能是"the type of a value",因为键必须是JSON中的字符串。如果路径已知(例如 .dataset),则可以使用 type 函数获取对象的类型:

jq '.dataset | type' < data.json

示例输出

"array"

编写同时依赖于键名和值的查询的最简单方法是使用“*_entries”过滤器系列之一。你的情况:

$ jq -c 'to_entries[] | [.key, (.value|type)]' data.json

["@context","string"]
["@id","string"]
["@type","string"]
["conformsTo","string"]
["describedBy","string"]
["dataset","array"]    

如果您希望以更易于阅读的方式呈现,请考虑使用@csv 或@tsv,例如

$ jq -r 'to_entries[] | [.key, (.value|type)] | @csv' data.json
"@context","string"
"@id","string"
"@type","string"
"conformsTo","string"
"describedBy","string"
"dataset","array"

或噪声较小:

$ jq -r 'to_entries[] | "\(.key) \(.value|type)"' data.json
@context string
@id string
@type string
conformsTo string
describedBy string
dataset array

奖金问题

这是第二个问题的参数化方法。让文件 query.jq 包含:

.[$key]|type

然后:

$ jq -r --arg key dataset -f query.jq data.json
array