santhosh-tekuri/jsonschema

Validation of unparsed JSON

Closed this issue · 4 comments

The purpose of libraries like this is to ensure that some blob of JSON is valid to some schema. However, it seems that I need to provide an already-parsed object for the validation to work.

What I'm doing right now is:

        // Compile the schema to validate the request body with.
	schema, err := jsonschema.CompileString("schema.json", getJSONSchema())
	if err != nil {
            ......
	}

        // Parse the request body into an untyped map for validation.
	var unmarshalled map[string]interface{} 
	if err = json.Unmarshal(body, &unmarshalled); err != nil {
            ......
	}

        // Actually validate the request body.
	if err = schema.Validate(unmarshalled); err != nil {
            ......
        }

Which works, but only when the body to be validated is a JSON object. If I ever wanted to use an array or a primitive value then this would fail.

It would be useful if you could pass either string []byte or even io.Reader into schema.Validate and it do the right thing with it.

Cheers

schema.Validate takes interface{}. so you can pass even array and primitive value to validate.

parsing json is not a territory for this library. you can use standard library to parse from string, []byte or io.Reader. you can even use some third party json parser libraries.

You can pass array and primitive values, but you need to have already parsed the JSON to do that. And that means you need to know what shape the JSON is.

For example, given the schema:

{
    "type": "array",
    "....."
}

And the JSON document:

{}

Trying to parse that into a []map[string]interface{} will fail, so I'll get a parse error instead of a schema validation error.

you can parse into interface{} as follows:

var body = []byte(`[1,2,3,4]`)
var unmarshalled interface{} 
if err = json.Unmarshal(body, &unmarshalled); err != nil {
          ......
}