简体   繁体   中英

how to use jq to flatten nested keys in the json

I am currently trying to process below json using jq commandline

cat api-docs.json  | jq '.paths'

{
...
...

  "paths": {
    "/pets": {
         "get": {
...
...
        "post": {
...
...
    "/pets/{petId}": {
         "get": {
...

https://jqplay.org/s/GV2zMjbCWK

I need a flattened info from swagger spec above

[ "GET /pets", "POST /pets", "GET /pets/{petId}" ]

is this even possible with jq command ?

with below I get each value independently

.paths|{k:keys,v:map(keys)}

But what I need is a way to combine keys at nested level to get above result ie array of "METHOD /PATH"

The following filter produces the results you want, as shown below:

.paths
| to_entries
| map( .key as $path
       | ( .value | to_entries[]
           | if .key == "get" then "GET"
             elif .key == "post" then "POST" 
             else empty end ) as $verb
       | $verb + " " + $path )

Output:

[
  "GET /pets",
  "POST /pets",
  "GET /pets/{petId}"
]

You may want to include more "verbs", or handle the verbs programmatically, eg

.paths
| to_entries
| map(( .value | to_entries[] | .key | ascii_upcase ) + " " + .key)

Discussion

The key to the solution here is to_entries , which produces an array of objects of the form {"key": _, "value": _ }. Apart from map , which here saves having to unpack the array and then repack it, the rest is syntax :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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