MCPcopy
hub / github.com/Velocidex/velociraptor / ParseJsonToMapWithSchema

Function ParseJsonToMapWithSchema

tools/json/validator.go:45–111  ·  view source on GitHub ↗
(
	json_string string, schemas []string,
	options ValidationOptions)

Source from the content-addressed store, hash-verified

43}
44
45func ParseJsonToMapWithSchema(
46 json_string string, schemas []string,
47 options ValidationOptions) (
48 res map[string]interface{},
49 schema *jsonschema.Schema, errs []error) {
50
51 json_data := []byte(json_string)
52
53 if len(schemas) == 0 {
54 schemas = []string{"{}"}
55 }
56
57 compiler := jsonschema.NewCompiler()
58 if options.Client != nil {
59 allowURLs := func(url string) (io.ReadCloser, error) {
60 return HTTPLoader(url, options)
61 }
62
63 compiler.RegisterLoader("http", allowURLs)
64 compiler.RegisterLoader("https", allowURLs)
65
66 } else {
67 // jsonschema by default installs handlers but this a security
68 // risk so we turn them off.
69 compiler.RegisterLoader("http", rejectURL)
70 compiler.RegisterLoader("https", rejectURL)
71 compiler.RegisterLoader("file", rejectURL)
72 }
73
74 schema_data := []byte(schemas[0])
75 schema, err := compiler.Compile(schema_data)
76 if err != nil {
77 return nil, nil, []error{DecorateError(schema_data, err)}
78 }
79
80 // Validate against the schema
81 validation_res := schema.Validate(json_data)
82 if !validation_res.IsValid() && len(validation_res.Errors) > 0 {
83 var errors []error
84 for _, details := range validation_res.Details {
85 for _, v := range details.Errors {
86 description := fmt.Sprintf("<red>%v</>", details.SchemaLocation)
87 description_any := details.Annotations["description"]
88 description_ptr, ok := description_any.(*string)
89 if ok && description_ptr != nil {
90 description = fmt.Sprintf("<red>%v</> (%v)", details.SchemaLocation,
91 *description_ptr)
92 }
93
94 errors = append(errors,
95 fmt.Errorf("%v: %w", description, v))
96 }
97 }
98
99 return nil, schema, errors
100 }
101
102 // Parse into a map with defaults

Callers 1

Calls 8

WrapFunction · 0.92
ElideFunction · 0.92
HTTPLoaderFunction · 0.85
DecorateErrorFunction · 0.85
CompileMethod · 0.80
ValidateMethod · 0.80
ErrorfMethod · 0.45
UnmarshalMethod · 0.45

Tested by

no test coverage detected