I already have a rough solution to this problem, but it's my first time working with JQ and I kind of feel like the result is a bit clunky, and I'd like advice on how to clean it up, or suggestions how I might use more idiomatic forms.
I have a swagger interface specification (full file here), and I want to extract info for each of the paths, the methods supported and the content-types expected in each case
For example, from:
{
"paths" : {
"/1.0/kb/paymentGateways/hosted/form/{accountId}" : {
"post" : {
"produces" : [
"application/json"
],
"consumes" : [
"application/json"
]
}
}
I would like to produce:
{
"path": "/1.0/kb/paymentGateways/hosted/form/{accountId}",
"method": "post",
"produces": "application/json",
"consumes": "application/json"
}
and here is the jq query I used to do this:
jq 'def nvl(n): (n//[null])[];'\
'.paths | keys[] as $path | .[$path] | keys[] as $method | .[$method] | '\
'{ $path, $method, produces: nvl(.produces), consumes: nvl(.consumes)}' swagger.json
Many Thanks
Apart from the formatting, you might consider defining nvl
as a 0-arity filter (which is more idiomatic and more efficient) or avoiding it altogether. Assuming a bash or bash-like shell, you could write:
jq 'def nvl: (.//[null])[];
.paths
| keys_unsorted[] as $path
| .[$path]
| keys_unsorted[] as $method
| .[$method]
| { $path,
$method,
produces: .produces | nvl,
consumes: .consumes | nvl
}' swagger.json
Consider also using the -f command line option.
Note that false // 0
evaluates to 0, so you might want to modify the def accordingly. It might be wise also to guard against other potential surprises.
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