santhosh-tekuri/jsonschema

Validate yaml file with the lib

Closed this issue · 8 comments

HI,

I've opened this question on stack overflow
https://stackoverflow.com/questions/49108078/validate-yaml-schema-with-golang-for-specifed-schema-structure-semantic

Can I use your library for my purpose ? by converting the yaml file json...

Thanks!

it tried the following:

package main

import (
	"fmt"
	"strings"

	"github.com/santhosh-tekuri/jsonschema"
	"gopkg.in/yaml.v2"
)

var yamlText = `
- one
- two
- 3
`

var schemaText = `
{
	"type": "array",
	"items": {
		"type": "string"
	}
}
`

func main() {
	fmt.Println(schemaText)
	var m interface{}
	err := yaml.Unmarshal([]byte(yamlText), &m)
	if err != nil {
		panic(err)
	}

	compiler := jsonschema.NewCompiler()
	if err := compiler.AddResource("schema.json", strings.NewReader(schemaText)); err != nil {
		panic(err)
	}
	schema, err := compiler.Compile("schema.json")
	if err != nil {
		panic(err)
	}
	if err := schema.ValidateInterface(m); err != nil {
		panic(err)
	}
}

it did not work. the yaml library unmarshals numbers into int. but this library expects float64 or json.Number

the library can be updated to work with int values...

fixed with 4eb6d64

now the above code works as expected

Thanks for this, it is exactly what I was looking for, but unfortunately it fails with a different input example.

If we use var yamlText = "key: value" instead, we get:
panic: invalid jsonType: map[interface {}]interface {}

This makes sense I think, as yaml keys can be of any type, whereas the check is looking for:
case map[string]interface{}:

Can you suggest any ways around this? Could it perhaps support key types of interface{} and dynamically check that they are strings?

Turns out you can solve this on the yaml parser side, without needing to touch jsonschema.

I used a tweaked version of this workaround, and apparently yaml.v3 will allow you to control what the default map type is.

The tweak, for reference, was replacing the final statement in the snippet with return v - as otherwise everything came out as a string.

@mykter
I checked how docker solves this. it simply converts map[interface{}]interface{} to map[string]interface{} recursively

see convertToStringKeysRecursive

nice, thanks.
Might be worth adding a note to the README that you can also do yaml validation with this pair of libraries, and perhaps linking to this issue? At the moment searching godoc or similar for 'yaml schema' doesn't include this package as a result.

added to README

see how to do it:
https://play.golang.org/p/Oeo-noJtKk_N