jsongomarshallingunmarshallinggoland

How to marshal raw text into JSON?


This is the content of the text file: "{\"tpl\":\"key = ${key}\\nkey1 = ${key1}\",\"metadata\":[{\"key\":\"key\"},{\"key\":\"key1\"}],\"format\":\"text\"}"

How can I unmarshal this into the given struct?

type templateMessage struct {
    TPL      string              `json:"tpl"`
    Metadata []map[string]string `json:"metadata"`
    Format   string              `json:"format"`
}

I've tried this:

func main() {
    var templateMsg templateMessage

    content, err := os.ReadFile("path-of-the-file/temp.txt")
    if err != nil {
        fmt.Println(err)
        return
    }

    err = json.Unmarshal(content, &templateMsg)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println(templateMsg)
}

But this gives me the following err: json: cannot unmarshal string into Go value of type main.templateMessage


Solution

  • The contents of the file is JSON encoded as JSON. Decode to a string, and then decode that string to the struct.

    func main() {
        var templateMsg templateMessage
    
        content, err := os.ReadFile("temp.txt")
        if err != nil {
            fmt.Println(err)
            return
        }
    
        var s string
        err = json.Unmarshal(content, &s)
        if err != nil {
            fmt.Println(err)
            return
        }
    
        err = json.Unmarshal([]byte(s), &templateMsg)
        if err != nil {
            fmt.Println(err)
            return
        }
    
        fmt.Println(templateMsg)
    }
    

    https://go.dev/play/p/yrmfixY5OGE