This is the sample in the Playground. The gist of the problem is that I am unable to decode / unmarshal this
Name := "TestName"
Desc := "Test Desc"
Body := []byte(`{"key": "value"}`)//simplest possible JSON but will have multiple levels
requestJson := fmt.Sprintf(`{"name": "%s","description": "%s","body": "%s"}`, Name, Desc, Body)
decoder := json.NewDecoder(strings.NewReader(requestJson))
err := decoder.Decode(&createRpt)
if err != nil {
fmt.Println("Report body is expected to be valid JSON", "error", err)
return
}
I have also tried to use the unmarshal
option as can be seen in the playground .
2
Answers
You have a typo in your json, remove the
"
around body’s value and it will be fixed:You should avoid, at all cost, formatting your own JSON like this. Just create a struct that you can marshal properly:
Demo
The key here is the
json.RawMessage
type. This essentially tellsjson.Marshal
that the value should not be unmarshalled, and accordingly it will just be copied over as-is (as a[]byte
). If you need to later on unmarshal the value ofBody
elsewhere, you can simply do so like this: