Skip to content

Instantly share code, notes, and snippets.

@hiroosak
Created December 13, 2014 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hiroosak/c70066ed92b0c847f499 to your computer and use it in GitHub Desktop.
Save hiroosak/c70066ed92b0c847f499 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"github.com/xeipuuv/gojsonschema"
"fmt"
)
type User struct {
Name string
Age uint16
Articles []Article
}
type Article struct {
Title string
Content string
}
func main() {
var jsonStr = `{
"Name": "Ken",
"Age": 32,
"Articles": [
{"Title": "Title A", "Content": "content A"},
{"Title": "Title B", "Content": "content B"}
]
}`
schema := `{
"type": "object",
"properties": {
"Name": {
"type": "string"
},
"Age": {
"type": "integer"
},
"Articles": {
"type": "array",
"items": {
"type": "object",
"properties": {
"Title": {
"type": "string"
},
"Content": {
"type": "string"
}
},
"additionalProperties": false,
"required": ["Title", "Content"]
}
}
},
"additionalProperties": false,
"required": ["Name", "Age", "Articles"]
}`
var j map[string]interface{}
err := json.Unmarshal([]byte(schema), &j)
if err != nil {
panic(err)
}
schemaDocument, err := gojsonschema.NewJsonSchemaDocument(j)
if err != nil {
panic(err)
}
var jsonBody interface{}
err = json.Unmarshal([]byte(jsonStr), &jsonBody)
if err != nil {
panic(err)
}
result := schemaDocument.Validate(jsonBody)
if result.Valid() == false {
panic("err")
}
var u User
err = json.Unmarshal([]byte(jsonStr), &u)
if err != nil {
panic(err)
}
fmt.Println(u) // {Ken 32 [{Title A content} {Title B content}]}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment