Esempio n. 1
0
func (d DataSet) ValidateAgainstSchema(data []map[string]interface{}, errors *[]error) {
	schema := d.MetaData.Schema

	if schema != nil {
		var jsonDoc map[string]interface{}
		err := json.Unmarshal(d.MetaData.Schema, &jsonDoc)

		if err != nil {
			panic(err)
		}

		schemaDocument, err := gojsonschema.NewJsonSchemaDocument(jsonDoc)
		if err != nil {
			panic(err)
		}
		for _, r := range data {
			result := schemaDocument.Validate(r)
			if !result.Valid() {
				for _, err := range result.Errors() {
					*errors = append(*errors, fmt.Errorf(err.Description))
				}
			}
		}
	}
}
Esempio n. 2
0
func MustSchema(doc string) *gojsonschema.JsonSchemaDocument {
	var value map[string]interface{}

	err := json.Unmarshal([]byte(doc), &value)
	if err != nil {
		panic(err)
	}

	schema, err := gojsonschema.NewJsonSchemaDocument(value)
	if err != nil {
		panic(err)
	}

	return schema
}
Esempio n. 3
0
func main() {
	var err error

	jsonData, err := getSchema()
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	schemaDocument, err := gojsonschema.NewJsonSchemaDocument(jsonData)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	// Loads the JSON to validate from a local file
	file := "./sample.json"
	jsonDocument, err := gojsonschema.GetFileJson("./" + file)
	fmt.Printf("Check ./%v\n", file)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	// Try to validate the Json against the schema
	result := schemaDocument.Validate(jsonDocument)

	// Deal with result
	if result.Valid() {
		fmt.Printf("The document is valid\n")
	} else {
		fmt.Printf("The document is not valid. see errors :\n")
		// Loop through errors
		for _, desc := range result.Errors() {
			fmt.Printf("- %s\n", desc)
		}
	}

}