From 069c3137b82691866b4f834d318633eac2d57861 Mon Sep 17 00:00:00 2001 From: sopak Date: Thu, 30 Mar 2017 18:12:05 +0200 Subject: [PATCH] add support for root-node In some cases I can get json with multiple schemas for example REST definition GET/POST/DELETE etc. This change will try to find node in json and use it as schema. --- generator.go | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/generator.go b/generator.go index e197c2f..ceb7b8a 100644 --- a/generator.go +++ b/generator.go @@ -27,6 +27,7 @@ var ( outputFile = kingpin.Flag("out-file", "filename for output; default is _schematype.go").Short('o').String() packageName = kingpin.Flag("package", `package name for generated file; default is "main"`).Default("main").String() rootTypeName = kingpin.Flag("root-type", `name of root type; default is generated from the filename`).String() + rootNodeName = kingpin.Flag("root-node", `name of root node of json; default is whole file`).String() typeNamesPrefix = kingpin.Flag("prefix", `prefix for non-root types`).String() inputFile = kingpin.Arg("input", "file containing a valid JSON schema").Required().ExistingFile() ) @@ -690,8 +691,22 @@ func main() { } var s metaSchema - if err = json.Unmarshal(file, &s); err != nil { - log.Fatalln("Error parsing JSON:", err) + if *rootNodeName != "" { + + var sub map[string]metaSchema + if err = json.Unmarshal(file, &sub); err != nil { + log.Fatalln("Error parsing JSON:", err) + } + node, ok := sub[*rootNodeName] + if ok == false { + log.Fatalln(fmt.Sprintf("Error JSON node '%s' does not exists:", *rootNodeName), err) + } + //log.Panicf("Error reading file %v:", node) + s = node + } else { + if err = json.Unmarshal(file, &s); err != nil { + log.Fatalln("Error parsing JSON:", err) + } } schemaName := strings.Split(filepath.Base(*inputFile), ".")[0]