Let's take this simple data file: http://data.cdc.gov/data.json
I know how to get the root key names:
jq keys_unsorted[] -r data.json
which produces:
@context
@id
@type
conformsTo
describedBy
dataset
And I know how to get the key types:
jq 'map(type)' data.json
Which produces:
[
"string",
"string",
"string",
"string",
"string",
"array"
]
Is there not some way of combining this in returning pairs? (what I am really trying to do is find the key name of the first root level array, if any). I can write a routine to figure it out, but this seem inelegant.
Bonus side question: 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 simplest approach to writing queries that depend on both key names and values is to use one of the "*_entries" family of filters. In your case:
$ jq -c 'to_entries[] | [.key, (.value|type)]' data.json
["@context","string"]
["@id","string"]
["@type","string"]
["conformsTo","string"]
["describedBy","string"]
["dataset","array"]
If you wanted this presented in a more human-readable fashion, consider using @csv or @tsv, e.g.
$ jq -r 'to_entries[] | [.key, (.value|type)] | @csv' data.json
"@context","string"
"@id","string"
"@type","string"
"conformsTo","string"
"describedBy","string"
"dataset","array"
Or with less noise:
$ jq -r 'to_entries[] | "\(.key) \(.value|type)"' data.json
@context string
@id string
@type string
conformsTo string
describedBy string
dataset array
Here's a parametric approach to the second question. Let the file query.jq contain:
.[$key]|type
Then:
$ jq -r --arg key dataset -f query.jq data.json
array
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With