4

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?

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Can I use interface for the map value only? because everything else is fixed except the map value type.
yes you can do that too. But this is an array you will have to use unmarshaller interface for dynamic values in json

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.