Skip to content

Generator fails on anyOf with array type containing enums #488

@jamesrom

Description

@jamesrom

Description

The go-jsonschema generator fails to handle anyOf schemas that contain an array type with enum items alongside other types.

Error Message

could not generate type for field "dayOfWeek": invalid type "array": unexpected type "array" here

Test Case

The following JSON Schema causes the generator to fail:

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "type": "object",
    "properties": {
        "dayOfWeek": {
            "anyOf": [
                {
                    "type": "array",
                    "items": {
                        "enum": [
                            "Monday",
                            "Tuesday",
                            "Wednesday",
                            "Thursday",
                            "Friday",
                            "Saturday",
                            "Sunday"
                        ]
                    }
                },
                {
                    "type": "string",
                    "enum": [
                        "All",
                        "Weekdays"
                    ]
                }
            ]
        }
    }
}

Expected Behavior

The generator should create a type that can handle either:

  • An array of weekday strings (Monday through Sunday)
  • A single string with special values ("All" or "Weekdays")

This is a valid JSON Schema pattern commonly used to accept either a list of specific values OR a shorthand string representation.

Root Cause

The error originates from pkg/codegen/utils.go:170 where the getTypeForSchema function explicitly rejects array and object types in certain contexts:

case schemas.TypeNameObject, schemas.TypeNameArray:
    return nil, fmt.Errorf("%w %q here", errUnexpectedType, jsType)

This appears to be a limitation in how the generator processes anyOf schemas containing complex types.

Reproduction

To reproduce this issue:

  1. Save the above JSON schema as tests/data/core/anyOf/anyOf.8.json
  2. Run: go test ./tests -v -run "TestCore/core/anyOf/anyOf.8"
  3. Observe the failure with the error message above

Impact

This prevents users from defining schemas with flexible input patterns that are valid according to the JSON Schema specification.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions