omissis / go-jsonschema

A tool to generate Go data types from JSON Schema definitions.
MIT License
579 stars 93 forks source link

Collapse `anyOf` with only one option? #296

Open stevekuznetsov opened 2 hours ago

stevekuznetsov commented 2 hours ago

If I have a schema like:

        "rings": {
          "type": "array",
          "description": "Array of the deployment ring object.",
            "items": {
                "anyOf": [
                    {
                        "$ref": "#/definitions/deploymentRing"
                    }
                ]
            }
      }

In a sense, it's equivalent to:

        "rings": {
          "type": "array",
          "description": "Array of the deployment ring object.",
          "items": {
              "type": "object",
              "$ref": "#/definitions/deploymentRing"
          }
      }

For users that generate Go types using a JSONSchema they do not control, the use of anyOf in the above example will generate []interface{}, which is unfortunate and very much so not ergonomic, either on generation or parsing. Would it be acceptable to generate a Go struct in these cases with a definite type for the slice, even if that is not perfectly what the author of the JSONSchema intended?

I am not sure, but it seems like there may be some other tool that generates these "loose" JSONSchemas with anyOf array items with only one type, perhaps also a bug in that generator. Would be awesome to work around such cases on the consumer end with this tool.

stevekuznetsov commented 2 hours ago

If this proposal is acceptable, I am happy to implement such a thing, also happy to hide it behind a flag.