Skip to content

Instantly share code, notes, and snippets.

@Streppel
Last active March 6, 2022 01:47
Show Gist options
  • Save Streppel/bd46f10e4066995775969de109e1aab6 to your computer and use it in GitHub Desktop.
Save Streppel/bd46f10e4066995775969de109e1aab6 to your computer and use it in GitHub Desktop.
partial JSON unmarshal to go struct
package main
import (
"encoding/json"
"fmt"
)
func main() {
var err error
myJson := []byte(`{"name": "Natan", "age": 27, "hobbies": ["programming", "inline_skatting"], "is_millionaire": false}`)
m := make(map[string]json.RawMessage)
if err := json.Unmarshal(myJson, &m); err != nil {
panic(err)
}
// partially unmarshall json to struct and keeps remaining data
var myStruct struct {
Name string `json:"name"`
Age int `json:"age"`
json.RawMessage
}
get(&myStruct.Name, m, "name")
get(&myStruct.Age, m, "age")
myStruct.RawMessage, err = json.Marshal(m)
if err != nil {
panic(err)
}
fmt.Println(myStruct)
}
func get(to interface{}, m map[string]json.RawMessage, s string) {
if err := json.Unmarshal(m[s], &to); err != nil {
panic(err)
}
delete(m, s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment