Skip to content

Instantly share code, notes, and snippets.

@Dynom
Created September 21, 2016 13:19
Show Gist options
  • Save Dynom/319f8d467512c3680c19a273a113ea4a to your computer and use it in GitHub Desktop.
Save Dynom/319f8d467512c3680c19a273a113ea4a to your computer and use it in GitHub Desktop.
Instead of (Un)marshalling into a valid struct, when you only care only about one field (in perhaps a dynamic JSON document) you could do the following
package main
import "fmt"
import "encoding/json"
const data = `{"a": "A", "b": "B", "c": "C"}`
func main() {
var objmap map[string]*json.RawMessage
err := json.Unmarshal([]byte(data), &objmap)
if err != nil {
fmt.Println(err)
}
objmap["a"].UnmarshalJSON(
[]byte(`"FOO"`),
)
fmt.Printf("a now is: %s\n", string(*objmap["a"]))
out, err := json.Marshal(objmap)
fmt.Println(string(out), err)
}
/* Output:
a now is: "FOO"
{"a":"FOO","b":"B","c":"C"} <nil>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment