Home > Software design >  Extracting objects attributes from Swagger JSON schema using jq
Extracting objects attributes from Swagger JSON schema using jq

Time:02-17

I want to extract objects name and their attributes (.properties) from .definitions part of swagger json file, like:

{
  "definitions": {
    "Pet": {
      "type": "object",
      "required": ["pet_type"],
      "properties": {
        "pet_type": {
          "type": "string"
        }
      },
      "discriminator": {
        "propertyName": "pet_type"
      }
    },
    "Dog": {
      "allOf": [{
          "$ref": "#/components/schemas/Pet"
        }, {
          "type": "object",
          "properties": {
            "bark": {
              "type": "boolean"
            },
            "breed": {
              "type": "string",
              "enum": ["Dingo", "Husky", "Retriever", "Shepherd"]
            }
          }
        }
      ]
    }
  }
}

to:

object_name:
  attribute_name

like:

Pet:
  pet_type
Dog:
  bark
  breed

The point is .properties sometimes come directly after object name and sometimes as part of allOf, anyOf, or oneOf

CodePudding user response:

Does this fit your needs?

jq -r '
  .definitions
  | to_entries[]
  | .key   ":", "  "   (
    .value
    | (., .allOf[], .anyOf[], .oneOf[] | .properties)? // {}
    | to_entries[].key
  )
'
Pet:
  pet_type
Dog:
  bark
  breed

Demo

  • Related