1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
|
package jsonschema
import (
"bytes"
"encoding/json"
"fmt"
"log"
"strings"
"github.com/buger/jsonparser"
)
type refs []*Ref
func (r *refs) String() string {
str := ""
if r != nil {
for _, r := range *r {
if r != nil && r.String != nil {
str += fmt.Sprintf("ref %s\n", *r.String)
} else {
str += "empty ref found\n"
}
}
}
return str
}
type pointers map[string]*Schema
func (p *pointers) String() string {
str := ""
if p != nil {
for k, s := range *p {
if s != nil {
str += fmt.Sprintf("pointer for %s\n%s\n", k, s.String())
} else {
str += fmt.Sprintf("pointer for %s is empty\n", k)
}
}
}
return str
}
type ValueType uint8
type SchemaProp uint8
// These are the same as jsonparser.ValueType - except Integer, which jsonparser does not have
const (
NotExist ValueType = iota
String
Number
Object
Array
Boolean
Null
Unknown
Integer
)
func (v ValueType) String() string {
switch v {
case NotExist:
return "non-existent"
case String:
return "string"
case Number:
return "number"
case Integer:
return "integer"
case Object:
return "object"
case Array:
return "array"
case Boolean:
return "boolean"
case Null:
return "null"
case Unknown:
fallthrough
default:
return "unknown"
}
}
func (v ValueType) ParserValueType() jsonparser.ValueType {
switch v {
case NotExist:
return jsonparser.NotExist
case String:
return jsonparser.String
case Number:
return jsonparser.Number
case Integer:
return jsonparser.Number
case Object:
return jsonparser.Object
case Array:
return jsonparser.Array
case Boolean:
return jsonparser.Boolean
case Null:
return jsonparser.Null
case Unknown:
fallthrough
default:
return jsonparser.Unknown
}
}
// TODO: Update with 20xx-xx props
const (
PropSchema SchemaProp = iota
PropID
PropIDDraft04
PropRef
PropComment
PropTitle
PropDescription
PropType
PropEnum
PropDefault
PropConst
PropExamples
PropReadOnly
PropWriteOnly
PropDefinitions
PropIf
PropThen
PropElse
PropAllOf
PropAnyOf
PropOneOf
PropNot
PropContentEncoding
PropContentMediaType
PropProperties
PropRequired
PropMaxProperties
PropMinProperties
PropDependencies
PropPatternProperties
PropAdditionalProperties
PropPropertyNames
PropItems
PropMaxItems
PropMinItems
PropUniqueItems
PropAdditionalItems
PropContains
PropMaxLength
PropMinLength
PropFormat
PropPattern
PropMultipleOf
PropMaximum
PropExclusiveMaximum
PropMinimum
PropExclusiveMinimum
)
// TODO: Update with 20xx-xx props
var propNames = [][]string{
PropSchema: {"$schema"},
PropID: {"$id"},
PropIDDraft04: {"id"},
PropRef: {"$ref"},
PropComment: {"$comment"},
PropTitle: {"title"},
PropDescription: {"description"},
PropType: {"type"},
PropEnum: {"enum"},
PropDefault: {"default"},
PropConst: {"const"},
PropExamples: {"examples"},
PropReadOnly: {"readOnly"},
PropWriteOnly: {"writeOnly"},
PropDefinitions: {"definitions"},
PropIf: {"if"},
PropThen: {"then"},
PropElse: {"else"},
PropAllOf: {"allOf"},
PropAnyOf: {"anyOf"},
PropOneOf: {"oneOf"},
PropNot: {"not"},
PropContentEncoding: {"contentEncoding"},
PropContentMediaType: {"contentMediaType"},
PropProperties: {"properties"},
PropRequired: {"required"},
PropMaxProperties: {"maxProperties"},
PropMinProperties: {"minProperties"},
PropDependencies: {"dependencies"},
PropPatternProperties: {"patternProperties"},
PropAdditionalProperties: {"additionalProperties"},
PropPropertyNames: {"propertyNames"},
PropItems: {"items"},
PropMaxItems: {"maxItems"},
PropMinItems: {"minItems"},
PropUniqueItems: {"uniqueItems"},
PropAdditionalItems: {"additionalItems"},
PropContains: {"contains"},
PropMaxLength: {"maxLength"},
PropMinLength: {"minLength"},
PropFormat: {"format"},
PropPattern: {"pattern"},
PropMultipleOf: {"multipleOf"},
PropMaximum: {"maximum"},
PropExclusiveMaximum: {"exclusiveMaximum"},
PropMinimum: {"minimum"},
PropExclusiveMinimum: {"exclusiveMinimum"},
}
// TODO: Update with 20xx-xx props
var nameToProp = map[string]SchemaProp{
"$schema": PropSchema,
"$id": PropID,
"id": PropIDDraft04,
"$ref": PropRef,
"$comment": PropComment,
"title": PropTitle,
"description": PropDescription,
"type": PropType,
"enum": PropEnum,
"default": PropDefault,
"const": PropConst,
"examples": PropExamples,
"readOnly": PropReadOnly,
"writeOnly": PropWriteOnly,
"definitions": PropDefinitions,
"if": PropIf,
"then": PropThen,
"else": PropElse,
"allOf": PropAllOf,
"anyOf": PropAnyOf,
"oneOf": PropOneOf,
"not": PropNot,
"contentEncoding": PropContentEncoding,
"contentMediaType": PropContentMediaType,
"properties": PropProperties,
"required": PropRequired,
"maxProperties": PropMaxProperties,
"minProperties": PropMinProperties,
"dependencies": PropDependencies,
"patternProperties": PropPatternProperties,
"additionalProperties": PropAdditionalProperties,
"propertyNames": PropPropertyNames,
"items": PropItems,
"maxItems": PropMaxItems,
"minItems": PropMinItems,
"uniqueItems": PropUniqueItems,
"additionalItems": PropAdditionalItems,
"contains": PropContains,
"maxLength": PropMaxLength,
"minLength": PropMinLength,
"format": PropFormat,
"pattern": PropPattern,
"multipleOf": PropMultipleOf,
"maximum": PropMaximum,
"exclusiveMaximum": PropExclusiveMaximum,
"minimum": PropMinimum,
"exclusiveMinimum": PropExclusiveMinimum,
}
func NewStringPtr(b []byte) *string {
unescaped, err := jsonparser.Unescape(b, nil)
if err != nil {
return nil
}
tmpStr := string(unescaped)
return &tmpStr
}
// func (e Ref) MarshalJSON() ([]byte, error) {
// b, err := json.Marshal(tmpEnum(e))
// return b,err
// }
type Enum []*Value
type tmpEnum Enum // To ensure MarshalJSON doesn't go haywire
func (e Enum) MarshalJSON() ([]byte, error) {
b, err := json.Marshal(tmpEnum(e))
return b, err
}
func NewEnum(jsonVal []byte, vt jsonparser.ValueType) (*Enum, error) {
var errs error
if vt == jsonparser.Array {
enum := Enum{}
jsonparser.ArrayEach(jsonVal, func(value []byte, dataType jsonparser.ValueType, offset int, parseErr error) {
if parseErr != nil {
errs = addError(parseErr, errs)
return
}
val, err := NewValue(value, dataType)
if err != nil {
errs = addError(err, errs)
return
}
enum = append(enum, val)
})
if errs != nil {
return nil, errs
}
return &enum, nil
}
return nil, fmt.Errorf("expected enum to be an array, got: %s", vt.String())
}
type Dependencies map[string]*Dependency
type tmpDependencies Dependencies // To ensure MarshalJSON doesn't go haywire
func (d Dependencies) MarshalJSON() ([]byte, error) {
b, err := json.Marshal(tmpDependencies(d))
return b, err
}
func NewDependencies(jsonVal []byte, vt jsonparser.ValueType, parentSchema *Schema) (*Dependencies, error) {
if vt == jsonparser.Object {
dependencies := Dependencies{}
err := jsonparser.ObjectEach(jsonVal, func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error {
var err error
dependencies[string(key)], err = NewDependency(value, dataType, parentSchema)
return err
})
if err != nil {
return nil, err
}
return &dependencies, nil
}
return nil, fmt.Errorf("expected properties to be object, got: %s", vt.String())
}
// Properties are build like this, instead of map[string]*Schema,
// to make it possible to Marshal with original sort order of fields
type NamedProperty struct {
Name string
Property *Schema
}
type Properties []*NamedProperty
// type tmpProperties Properties // To ensure MarshalJSON doesn't go haywire
func (p Properties) GetProperty(name string) (*NamedProperty, bool) {
for _, prop := range p {
if prop.Name == name {
return prop, true
}
}
return nil, false
}
func (p Properties) MarshalJSON() ([]byte, error) {
propsData := []byte("{")
buf := bytes.NewBuffer(propsData)
for i, prop := range p {
fieldVal, err := json.Marshal(prop.Property)
if err != nil {
log.Println(err)
return nil, err
}
escapedFieldName := strings.ReplaceAll(prop.Name, `\`, `\\`)
escapedFieldName = strings.ReplaceAll(escapedFieldName, `"`, `\"`)
escapedFieldName = strings.ReplaceAll(escapedFieldName, "\n", `\n`)
escapedFieldName = strings.ReplaceAll(escapedFieldName, "\r", `\r`)
escapedFieldName = strings.ReplaceAll(escapedFieldName, "\t", `\t`)
escapedFieldName = strings.ReplaceAll(escapedFieldName, "\f", `\u000c`)
fmt.Fprintf(buf, `"%s": %s`, escapedFieldName, string(fieldVal))
if i < len(p)-1 {
fmt.Fprint(buf, `,`)
}
}
fmt.Fprint(buf, `}`)
return buf.Bytes(), nil
}
func NewProperties(jsonVal []byte, vt jsonparser.ValueType, parentSchema *Schema) (*Properties, error) {
if vt == jsonparser.Object {
props := Properties{}
err := jsonparser.ObjectEach(jsonVal, func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error {
var err error
prop := &NamedProperty{
Name: string(key),
}
prop.Property, err = parentSchema.Parse(value)
if err != nil {
return err
}
props = append(props, prop)
return err
})
if err != nil {
return nil, err
}
return &props, nil
}
return nil, fmt.Errorf("expected properties to be object, got: %s", vt.String())
}
// type Definitions map[string]*Schema
// type tmpDefinitions Definitions // To ensure MarshalJSON doesn't go haywire
// func (p Definitions) MarshalJSON() ([]byte, error) {
// b, err := json.Marshal(tmpDefinitions(p))
// return b, err
// }
// func NewDefinitions(jsonVal []byte, vt jsonparser.ValueType, parentSchema *Schema) (*Properties, error) {
// if vt == jsonparser.Object {
// props := Properties{schemas: map[string]*Schema{}, sortedFields: []string{}}
// err := jsonparser.ObjectEach(jsonVal, func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error {
// var err error
// props.schemas[string(key)], err = parentSchema.Parse(value)
// props.sortedFields = append(props.sortedFields, string(key))
// return err
// })
// if err != nil {
// return nil, err
// }
// return &props, nil
// }
// return nil, fmt.Errorf("expected properties to be object, got: %s", vt.String())
// }
type Schemas []*Schema
type tmpSchemas Schemas // To ensure MarshalJSON doesn't go haywire
func (s Schemas) MarshalJSON() ([]byte, error) {
b, err := json.Marshal(tmpSchemas(s))
return b, err
}
func NewSubSchemas(jsonVal []byte, vt jsonparser.ValueType, parentSchema *Schema) (*Schemas, error) {
var errs error
if vt == jsonparser.Array {
schemas := Schemas{}
jsonparser.ArrayEach(jsonVal, func(value []byte, dataType jsonparser.ValueType, offset int, parseErr error) {
if parseErr != nil {
errs = addError(parseErr, errs)
return
}
if dataType == jsonparser.Object || dataType == jsonparser.Boolean {
schema, err := parentSchema.Parse(value)
if err != nil {
errs = addError(err, errs)
return
}
schemas = append(schemas, schema)
} else {
errs = addError(fmt.Errorf("expected type to be object or boolean, got: %s", vt.String()), errs)
}
})
if errs != nil {
return nil, errs
}
return &schemas, nil
}
return nil, fmt.Errorf("expected enum to be an array, got: %s", vt.String())
}
type Strings []*string
type tmpStrings Strings // To ensure MarshalJSON doesn't go haywire
func (p Strings) MarshalJSON() ([]byte, error) {
b, err := json.Marshal(tmpStrings(p))
return b, err
}
func NewStrings(jsonVal []byte, vt jsonparser.ValueType) (*Strings, error) {
var errs error
if vt == jsonparser.Array {
strings := Strings{}
jsonparser.ArrayEach(jsonVal, func(value []byte, dataType jsonparser.ValueType, offset int, parseErr error) {
if parseErr != nil {
errs = addError(parseErr, errs)
return
}
if dataType == jsonparser.String {
unescaped, err := jsonparser.Unescape(value, nil)
if err != nil {
errs = addError(parseErr, errs)
return
}
tmpStr := string(unescaped)
strings = append(strings, &tmpStr)
} else {
errs = addError(fmt.Errorf("expected type to be string, got: %s", vt.String()), errs)
}
})
if errs != nil {
return nil, errs
}
return &strings, nil
}
return nil, fmt.Errorf("expected enum to be an array, got: %s", vt.String())
}
type Values []*Value
type tmpValues Values // To ensure MarshalJSON doesn't go haywire
func (v Values) MarshalJSON() ([]byte, error) {
b, err := json.Marshal(tmpValues(v))
return b, err
}
func NewValues(jsonVal []byte, vt jsonparser.ValueType) (*Values, error) {
var errs error
if vt == jsonparser.Array {
values := Values{}
jsonparser.ArrayEach(jsonVal, func(value []byte, dataType jsonparser.ValueType, offset int, parseErr error) {
if parseErr != nil {
errs = addError(parseErr, errs)
return
}
val, err := NewValue(value, dataType)
if err != nil {
errs = addError(err, errs)
return
}
values = append(values, val)
})
if errs != nil {
return nil, errs
}
return &values, nil
}
return nil, fmt.Errorf("expected enum to be an array, got: %s", vt.String())
}
|