How to decode or unmarshal embedded JSON in Golang?

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 .

>Solution :

You have a typo in your json, remove the " around body’s value and it will be fixed:

requestJson := fmt.Sprintf(`{"name": "%s","description": "%s","body": %s}`, Name, Desc, Body)

Leave a Reply