Created
January 31, 2022 13:58
-
-
Save Integralist/040909cecc68ee0e2f1dd5b91e5cafb6 to your computer and use it in GitHub Desktop.
[Golang handle unknown json data structure] #go #golang #json #marshal #unmarshal
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" | |
"log" | |
) | |
func main() { | |
var ( | |
i interface{} | |
m map[string]interface{} | |
ok bool | |
err error | |
data []byte | |
) | |
data = []byte(`{"name":"example", "foo":123, "bar":true, "baz":"something"}`) | |
if err = json.Unmarshal(data, &i); err != nil { | |
log.Fatal(err) | |
} | |
fmt.Printf("i: %+v\n", i) | |
if m, ok = i.(map[string]interface{}); !ok { | |
log.Fatal("failed to type assert data") | |
} | |
fmt.Printf("m: %+v\n", m) | |
if _, ok := m["name"]; ok { | |
m["name"] = "dynamic" | |
} | |
fmt.Printf("m: %+v\n", m) | |
if data, err = json.Marshal(m); err != nil { | |
log.Fatal(err) | |
} | |
fmt.Printf("data: %+v\n", string(data)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment