Skip to content

Go: missing omitempty tag for optional arrays #1288

@pastamoe

Description

@pastamoe

If an optional field is of type array, quicktype doesn't add the omitempty tag

example schema:

schema.json

{
  "type": "object",
  "properties": {
    "id": {
      "type": "string"
    },
    "name": {
      "type": "string"
    },
    "users": {
      "type": "array",
      "items": {
        "type": "string",
        "format": "uuid"
      }
    }
  },
  "required": ["id"]
}

generate code via quicktype -s schema --just-types -o types.go schema.json

types.go

type Types struct {
        ID    string   `json:"id"`            
        Name  *string  `json:"name,omitempty"`
        Users []string `json:"users"`         
}

The only required field is ID, so Name correctly gets the omitempty tag. But Users is missing it. Because of that, marshaling an instance of Types with a nil Users array will always generate an invalid json (i.e. won't pass validation with the above schema):

{
    "id":"",
    "users":null
}

The omitempty tag must be added for optional arrays also, so marshaling leaves them out.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions