Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ordered jsonschema def #840

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 33 additions & 11 deletions jsonschema/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ const (
Boolean DataType = "boolean"
)

// OrderedProperties represents an ordered map of property names to their definitions
type OrderedProperties struct {
Keys []string
Values map[string]Definition
}

// Definition is a struct for describing a JSON Schema.
// It is fairly limited, and you may have better luck using a third-party library.
type Definition struct {
Expand All @@ -35,7 +41,7 @@ type Definition struct {
// one element, where each element is unique. You will probably only use this with strings.
Enum []string `json:"enum,omitempty"`
// Properties describes the properties of an object, if the schema type is Object.
Properties map[string]Definition `json:"properties,omitempty"`
Properties OrderedProperties `json:"-"`
// Required specifies which properties are required, if the schema type is Object.
Required []string `json:"required,omitempty"`
// Items specifies which data type an array contains, if the schema type is Array.
Expand All @@ -49,15 +55,31 @@ type Definition struct {
}

func (d *Definition) MarshalJSON() ([]byte, error) {
if d.Properties == nil {
d.Properties = make(map[string]Definition)
}
type Alias Definition
return json.Marshal(struct {
Alias
aux := struct {
*Alias
Properties json.RawMessage `json:"properties,omitempty"`
}{
Alias: (Alias)(*d),
})
Alias: (*Alias)(d),
}

if len(d.Properties.Keys) > 0 {
orderedProps := make(map[string]json.RawMessage)
for _, key := range d.Properties.Keys {
value, err := json.Marshal(d.Properties.Values[key])
if err != nil {
return nil, err
}
orderedProps[key] = value
}
var err error
aux.Properties, err = json.Marshal(orderedProps)
if err != nil {
return nil, err
}
}

return json.Marshal(aux)
}

func (d *Definition) Unmarshal(content string, v any) error {
Expand Down Expand Up @@ -114,8 +136,8 @@ func reflectSchemaObject(t reflect.Type) (*Definition, error) {
var d = Definition{
Type: Object,
AdditionalProperties: false,
Properties: OrderedProperties{Keys: make([]string, 0), Values: make(map[string]Definition)},
}
properties := make(map[string]Definition)
var requiredFields []string
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
Expand All @@ -139,7 +161,8 @@ func reflectSchemaObject(t reflect.Type) (*Definition, error) {
if description != "" {
item.Description = description
}
properties[jsonTag] = *item
d.Properties.Keys = append(d.Properties.Keys, jsonTag)
d.Properties.Values[jsonTag] = *item

if s := field.Tag.Get("required"); s != "" {
required, _ = strconv.ParseBool(s)
Expand All @@ -149,6 +172,5 @@ func reflectSchemaObject(t reflect.Type) (*Definition, error) {
}
}
d.Required = requiredFields
d.Properties = properties
return &d, nil
}
210 changes: 81 additions & 129 deletions jsonschema/json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,201 +11,153 @@ import (
func TestDefinition_MarshalJSON(t *testing.T) {
tests := []struct {
name string
def jsonschema.Definition
def any
want string
}{
{
name: "Test with empty Definition",
def: jsonschema.Definition{},
want: `{"properties":{}}`,
},
{
name: "Test with Definition properties set",
def: jsonschema.Definition{
Type: jsonschema.String,
Description: "A string type",
Properties: map[string]jsonschema.Definition{
"name": {
Type: jsonschema.String,
},
},
},
def: struct{}{},
want: `{
"type":"string",
"description":"A string type",
"properties":{
"name":{
"type":"string",
"properties":{}
}
}
"type":"object",
"additionalProperties":false
}`,
},
{
name: "Test with nested Definition properties",
def: jsonschema.Definition{
Type: jsonschema.Object,
Properties: map[string]jsonschema.Definition{
"user": {
Type: jsonschema.Object,
Properties: map[string]jsonschema.Definition{
"name": {
Type: jsonschema.String,
},
"age": {
Type: jsonschema.Integer,
},
},
},
},
},
def: struct {
User struct {
Name string `json:"name"`
Age int `json:"age"`
} `json:"user"`
}{},
want: `{
"type":"object",
"properties":{
"user":{
"type":"object",
"properties":{
"name":{
"type":"string",
"properties":{}
"type":"string"
},
"age":{
"type":"integer",
"properties":{}
"type":"integer"
}
}
}
}
},
"additionalProperties":false,
"required":["user"]
}`,
},
{
name: "Test with complex nested Definition",
def: jsonschema.Definition{
Type: jsonschema.Object,
Properties: map[string]jsonschema.Definition{
"user": {
Type: jsonschema.Object,
Properties: map[string]jsonschema.Definition{
"name": {
Type: jsonschema.String,
},
"age": {
Type: jsonschema.Integer,
},
"address": {
Type: jsonschema.Object,
Properties: map[string]jsonschema.Definition{
"city": {
Type: jsonschema.String,
},
"country": {
Type: jsonschema.String,
},
},
},
},
},
},
},
def: struct {
User struct {
Name string `json:"name"`
Age int `json:"age"`
Address struct {
City string `json:"city"`
Country string `json:"country"`
} `json:"address"`
} `json:"user"`
}{},
want: `{
"type":"object",
"properties":{
"user":{
"type":"object",
"properties":{
"name":{
"type":"string",
"properties":{}
"type":"string"
},
"age":{
"type":"integer",
"properties":{}
"type":"integer"
},
"address":{
"type":"object",
"properties":{
"city":{
"type":"string",
"properties":{}
"type":"string"
},
"country":{
"type":"string",
"properties":{}
"type":"string"
}
}
}
}
},
"additionalProperties":false,
"required":["name","age","address"]
}
}
},
"additionalProperties":false,
"required":["user"]
}`,
},
{
name: "Test with Array type Definition",
def: jsonschema.Definition{
Type: jsonschema.Array,
Items: &jsonschema.Definition{
Type: jsonschema.String,
},
Properties: map[string]jsonschema.Definition{
"name": {
Type: jsonschema.String,
},
},
},
def: []string{},
want: `{
"type":"array",
"items":{
"type":"string",
"properties":{

}
},
"properties":{
"name":{
"type":"string",
"properties":{}
}
"type":"string"
}
}`,
},
{
name: "Test order prevention",
def: struct {
C string `json:"c"`
A int `json:"a"`
B bool `json:"b"`
}{},
want: `{
"type":"object",
"properties":{
"c":{
"type":"string"
},
"a":{
"type":"integer"
},
"b":{
"type":"boolean"
}
},
"additionalProperties":false,
"required":["c","a","b"]
}
`,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
wantBytes := []byte(tt.want)
var want map[string]interface{}
err := json.Unmarshal(wantBytes, &want)
var wantDef jsonschema.Definition
err := json.Unmarshal(wantBytes, &wantDef)
if err != nil {
t.Errorf("Failed to Unmarshal JSON: error = %v", err)
return
}

got := structToMap(t, tt.def)
gotPtr := structToMap(t, &tt.def)

if !reflect.DeepEqual(got, want) {
t.Errorf("MarshalJSON() got = %v, want %v", got, want)
schema, err := jsonschema.GenerateSchemaForType(tt.def)
if err != nil {
t.Errorf("Failed to Unmarshal JSON: error = %v", err)
return
}
if !reflect.DeepEqual(gotPtr, want) {
t.Errorf("MarshalJSON() gotPtr = %v, want %v", gotPtr, want)
gotBytes, err := schema.MarshalJSON()
if err != nil {
t.Errorf("Failed to Marshal JSON: error = %v", err)
return
}
var gotDef jsonschema.Definition
err = json.Unmarshal(gotBytes, &gotDef)
if err != nil {
t.Errorf("Failed to Unmarshal JSON: error = %v", err)
return
}
if !reflect.DeepEqual(wantDef, gotDef) {
t.Errorf("Definition.MarshalJSON() = %v, want %v", gotDef, wantDef)
}
})
}
}

func structToMap(t *testing.T, v any) map[string]any {
t.Helper()
gotBytes, err := json.Marshal(v)
if err != nil {
t.Errorf("Failed to Marshal JSON: error = %v", err)
return nil
}

var got map[string]interface{}
err = json.Unmarshal(gotBytes, &got)
if err != nil {
t.Errorf("Failed to Unmarshal JSON: error = %v", err)
return nil
}
return got
}
2 changes: 1 addition & 1 deletion jsonschema/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func validateObject(schema Definition, data any) bool {
return false
}
}
for key, valueSchema := range schema.Properties {
for key, valueSchema := range schema.Properties.Values {
value, exists := dataMap[key]
if exists && !Validate(valueSchema, value) {
return false
Expand Down
Loading
Loading