skip to Main Content

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


  1. 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)
    
    Login or Signup to reply.
  2. You should avoid, at all cost, formatting your own JSON like this. Just create a struct that you can marshal properly:

    type Foo struct {
        Name        string          `json:"name"`
        Description string          `json:"description"`
        Body        json.RawMessage `json:"body"`
    }
    
    func main() {
        name, desc := "Test Name", "Test description, lorum ipsum"
        body := []byte(`{"key": "value"}`)
        jData, err := json.Marshal(Foo{
           Name:        name,
           Description: desc,
           Body:        body,
        })
        if err != nil {
            // handle error
        }
        fmt.Printf("%sn", string(jData))
    }
    

    Demo

    The key here is the json.RawMessage type. This essentially tells json.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 of Body elsewhere, you can simply do so like this:

    data := map[string]any{}
    if err := json.Unmarshal([]byte(t.Body), &data); err != nil {
        // handle error
    }
    fmt.Printf("Unmarshalled: %#vn", data)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search