Search code examples
jsongogo-map

How to parse a JSON into a map with variable type in Golang


I have the following JSON response from the Salt-Stack API:

{
    "return": [{
        "<UUID1>": true,
        "<UUID2>": "Minion did not return. [No response]",
        "<UUID3>": true,
        "<UUID4>": false
    }]
}

I usually use a map structure to unmarshall it in Go:

type getMinionsStatusResponse struct {
    Returns     []map[string]bool `json:"return"`
}

But due to the second row where an error response is returned (in string format) instead of the boolean, I got the following error: json: cannot unmarshal string into Go value of type bool

I wonder how I can marshall this JSON format in Golang using the encoding/json package?


Solution

  • For unmarshalling dynamic json where output is different use interface to unmarshal the same. It will unmarshal whole json as it is structured with any type inside it.

    package main
    
    import (
        "fmt"
        "encoding/json"
    )
    
    func main() {
        jsonbytes := []byte(`{
            "return": [{
                "<UUID1>": true,
                "<UUID2>": "Minion did not return. [No response]",
                "<UUID3>": true,
                "<UUID4>": false
                }]
        }`)
        var v interface{}
        if err := json.Unmarshal(jsonbytes, &v); err != nil{
            fmt.Println(err)
        }
        fmt.Println(v)
    }
    

    Playground