Skip to content

Instantly share code, notes, and snippets.

@mogeta mogeta/main.go
Created Sep 19, 2013

Embed
What would you like to do?
json data to struct code
package main
import (
"bytes"
"crypto/md5"
"encoding/json"
"flag"
"fmt"
"io"
)
const APP_VERSION = "0.1"
type result struct {
Data map[string]string
}
// The flag package provides a default help printer via -h switch
var versionFlag *bool = flag.Bool("v", false, "Print the version number.")
var jsonFlag *string = flag.String("j", "[1,2,3]", "Print the version number.")
var jsonStr result //make(map[string]string)
func main() {
flag.Parse() // Scan the arguments list
jsonStr = result{Data: make(map[string]string)}
if *versionFlag {
fmt.Println("Version:", APP_VERSION)
fmt.Printf("%s\n", *jsonFlag)
}
b := []byte(*jsonFlag)
var f interface{}
json.Unmarshal(b, &f)
fmt.Println("parsing...")
switch ff := f.(type) {
case []interface{}:
parseArray("Array", ff)
case map[string]interface{}:
parse("Data", ff)
default:
fmt.Println("error")
}
fmt.Println("---- result ----")
jsonStr.Print()
}
func parseArray(name string, t []interface{}) (s string) {
if len(t) == 0 {
return "[]interface{}"
}
switch vv := t[0].(type) {
case bool:
return fmt.Sprintf("[]%T", vv)
case string:
return fmt.Sprintf("[]%T", vv)
case float64:
return fmt.Sprintf("[]%T", vv)
case map[string]interface{}:
parse(name, vv)
return fmt.Sprintf("[]%s", name)
case []interface{}:
return fmt.Sprintf("[]%s", parseArray(name, vv))
default:
}
return "[]interface{}"
}
func parse(t string, m map[string]interface{}) {
var buffer bytes.Buffer
buffer.WriteString(fmt.Sprintf("type %s struct {\n", t))
//fmt.Println("type ", t, " struct {")
for k, v := range m {
switch vv := v.(type) {
case bool:
//fmt.Println(k, "\t", vv)
buffer.WriteString(fmt.Sprintf("\t%s\t%T\n", k, vv))
case string:
//fmt.Println(k, "\t", vv)
buffer.WriteString(fmt.Sprintf("\t%s\t%T\n", k, vv))
case float64:
//fmt.Println(k, "\t", vv)
buffer.WriteString(fmt.Sprintf("\t%s\t%T\n", k, vv))
case map[string]interface{}:
//fmt.Println(k, "is map", vv)
buffer.WriteString(fmt.Sprintf("\t%s\t%s\n", k, k))
parse(k, vv)
case []interface{}:
//fmt.Println(k, "is an array:")
buffer.WriteString(fmt.Sprintf("\t%s\t%s\n", k, parseArray(k, vv)))
default:
//fmt.Println("unexpected type %T", vv)
}
}
buffer.WriteString("}")
jsonStr.Insert(buffer.String())
}
func (f *result) Insert(s string) {
h := md5.New()
io.WriteString(h, s)
f.Data[fmt.Sprintf("%x", h.Sum(nil))] = s
}
func (f result) Print() {
for _, v := range f.Data {
defer fmt.Println(v)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.