[英]How to parse a JSON into a map with variable type in Golang
我有來自Salt-Stack API的以下JSON響應:
{
"return": [{
"<UUID1>": true,
"<UUID2>": "Minion did not return. [No response]",
"<UUID3>": true,
"<UUID4>": false
}]
}
我通常使用地圖結構在Go中解組它:
type getMinionsStatusResponse struct {
Returns []map[string]bool `json:"return"`
}
但由於返回錯誤響應的第二行(以字符串格式)而不是布爾值,我得到以下錯誤: json: cannot unmarshal string into Go value of type bool
我想知道如何使用encoding/json
包在Golang中編組這個JSON格式?
對於解組輸出不同的動態json,使用接口來解組相同的。 它將解組整個json,因為它內部有任何類型的結構。
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)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.