Created
September 21, 2016 13:19
-
-
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
This file contains 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 "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