Skip to content
Permalink
Browse files

record raw input JSON document for schema to support JSON Schema exte…

…nsions
  • Loading branch information...
sqs committed Feb 5, 2019
1 parent 170ed4b commit 7939fa138765c923e744cac5dca74eacac048c9c
Showing with 32 additions and 2 deletions.
  1. +9 −2 jsonschema/schema.go
  2. +23 −0 jsonschema/schema_test.go
@@ -53,6 +53,11 @@ type Schema struct {
Type PrimitiveTypeList `json:"type,omitempty"`
UniqueItems *bool `json:"uniqueItems,omitempty"`

// Raw is the raw JSON document that this schema was unmarshaled from, if any. It can be used to
// retrieve and set custom properties (such as for extensions to JSON Schema). It is omitted
// from the JSON encoding of this value.
Raw *json.RawMessage `json:"-"`

IsEmpty bool `json:"-"` // the schema is "true"
IsNegated bool `json:"-"` // the schema is "false"

@@ -92,16 +97,18 @@ func (s *Schema) MarshalJSON() ([]byte, error) {

// UnmarshalJSON implements json.Unmarshaler.
func (s *Schema) UnmarshalJSON(data []byte) error {
raw := (*json.RawMessage)(&data)
switch {
case bytes.Equal(data, trueBytes):
*s = Schema{IsEmpty: true}
*s = Schema{IsEmpty: true, Raw: raw}
case bytes.Equal(data, falseBytes):
*s = Schema{IsNegated: true}
*s = Schema{IsNegated: true, Raw: raw}
default:
type schema2 Schema
if err := json.Unmarshal(data, (*schema2)(s)); err != nil {
return errors.WithMessage(err, "failed to unmarshal JSON Schema")
}
s.Raw = raw
}
return nil
}
@@ -4,6 +4,7 @@ import (
"bytes"
"encoding/json"
"io/ioutil"
"reflect"
"testing"

"github.com/sourcegraph/go-jsonschema/internal/testutil"
@@ -32,4 +33,26 @@ func TestSample(t *testing.T) {
}
}

func TestRaw(t *testing.T) {
t.Run("marshal", func(t *testing.T) {
b, err := json.Marshal(Schema{Comment: strptr("c")})
if err != nil {
t.Fatal(err)
}
if want := `{"$comment":"c"}`; string(b) != want {
t.Errorf("got %s, want %s", b, want)
}
})
t.Run("unmarshal", func(t *testing.T) {
input := []byte(`{"$comment":"c"}`)
var o Schema
if err := json.Unmarshal([]byte(input), &o); err != nil {
t.Fatal(err)
}
if want := (Schema{Comment: strptr("c"), Raw: (*json.RawMessage)(&input)}); !reflect.DeepEqual(o, want) {
t.Errorf("got %+v, want %+v", o, want)
}
})
}

func strptr(s string) *string { return &s }

0 comments on commit 7939fa1

Please sign in to comment.
You can’t perform that action at this time.