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?

Himanshu
  • 12,071
  • 7
  • 46
  • 61
user892960
  • 309
  • 2
  • 11

1 Answers1

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

Himanshu
  • 12,071
  • 7
  • 46
  • 61
  • Can I use `interface` for the map value only? because everything else is fixed except the map value type. – user892960 Apr 27 '18 at 15:18
  • yes you can do that too. But this is an array you will have to use unmarshaller interface for dynamic values in json – Himanshu Apr 27 '18 at 15:19