forked from Azure/acs-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
strictjson.go
76 lines (72 loc) · 1.95 KB
/
strictjson.go
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
package api
import (
"encoding/json"
"fmt"
"reflect"
"strings"
)
func checkJSONKeys(data []byte, types ...reflect.Type) error {
var raw interface{}
if e := json.Unmarshal(data, &raw); e != nil {
return e
}
o := raw.(map[string]interface{})
return checkMapKeys(o, types...)
}
func checkMapKeys(o map[string]interface{}, types ...reflect.Type) error {
fieldMap := createJSONFieldMap(types)
for k, v := range o {
f, present := fieldMap[strings.ToLower(k)]
if !present {
return fmt.Errorf("Unknown JSON tag %s", k)
}
if f.Type.Kind() == reflect.Struct && v != nil {
if childMap, exists := v.(map[string]interface{}); exists {
if e := checkMapKeys(childMap, f.Type); e != nil {
return e
}
}
}
if f.Type.Kind() == reflect.Slice && v != nil {
elementType := f.Type.Elem()
if elementType.Kind() == reflect.Ptr {
elementType = elementType.Elem()
}
if childSlice, exists := v.([]interface{}); exists {
for _, child := range childSlice {
if childMap, exists := child.(map[string]interface{}); exists {
if e := checkMapKeys(childMap, elementType); e != nil {
return e
}
}
}
}
}
if f.Type.Kind() == reflect.Ptr && v != nil {
elementType := f.Type.Elem()
if childMap, exists := v.(map[string]interface{}); exists {
if e := checkMapKeys(childMap, elementType); e != nil {
return e
}
}
}
}
return nil
}
func createJSONFieldMap(types []reflect.Type) map[string]reflect.StructField {
fieldMap := make(map[string]reflect.StructField)
// Combine the permitted JSON fields from all types - handles the case
// where we need to see the same JSON as a TypeMeta and a ContainerService
for _, t := range types {
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
tag := f.Tag
fieldJSON := tag.Get("json")
if fieldJSON != "" {
fieldJSONkey := strings.SplitN(fieldJSON, ",", 2)[0]
fieldMap[strings.ToLower(fieldJSONkey)] = f
}
}
}
return fieldMap
}