Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get root keys and key types using jq

Tags:

json

types

key

jq

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)?

like image 201
Narwhal Avatar asked Dec 15 '22 01:12

Narwhal


1 Answers

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

Bonus question

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
like image 113
peak Avatar answered Dec 17 '22 01:12

peak