Created
September 8, 2020 00:52
-
-
Save lotusirous/fb7fe706ef5dcbecb856fd0abf5af87f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "encoding/json" | |
| "fmt" | |
| "os" | |
| ) | |
| type Foo struct { | |
| Object map[string]string `json:"obj"` | |
| keys []string | |
| } | |
| var _ json.Marshaler = &Foo{} | |
| var _ json.Unmarshaler = &Foo{} | |
| func (f *Foo) UnmarshalJSON(data []byte) error { | |
| var out map[string]interface{} | |
| f.Object = make(map[string]string) | |
| err := json.Unmarshal(data, &out) | |
| if err != nil { | |
| return err | |
| } | |
| for k, v := range out { | |
| switch val := v.(type) { | |
| case string: | |
| fmt.Println(k, val, "(string)") | |
| default: // interface | |
| obj := val.(map[string]interface{}) | |
| for k, v := range obj { | |
| val := v.(string) | |
| f.keys = append(f.keys, k) | |
| f.Object[k] = val | |
| } | |
| } | |
| } | |
| return nil | |
| } | |
| func (f *Foo) MarshalJSON() ([]byte, error) { | |
| res := append([]byte(nil), '{') | |
| length := len(f.keys) | |
| for idx, k := range f.keys { | |
| v := f.Object[k] | |
| res = append(res, fmt.Sprintf("%q:", k)...) | |
| var b []byte | |
| b, err := json.Marshal(v) // add value | |
| if err != nil { | |
| return nil, err | |
| } | |
| res = append(res, b...) | |
| if idx < length-1 { | |
| res = append(res, []byte(",")...) | |
| } | |
| } | |
| res = append(res, '}') | |
| return res, nil | |
| } | |
| func main() { | |
| data := ` | |
| { | |
| "obj": { | |
| "foo": "bar", | |
| "fooz": "barz" | |
| } | |
| } | |
| ` | |
| fo := new(Foo) | |
| json.Unmarshal([]byte(data), &fo) | |
| fmt.Println("[+] After json.Unmarshal", fo) | |
| b, err := json.Marshal(fo) | |
| if err != nil { | |
| fmt.Println("marshal failed", err) | |
| } | |
| fmt.Println("after marshaling") | |
| os.Stdout.Write(b) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment