SoFunction
Updated on 2025-03-05

golang implements conversion when json type is uncertain

When converting json to a structure, you often encounter situations where you cannot determine a certain field type. In Go, you can use any type of interface to solve it.

// convert json to struct
// type uncertain
package main
import (
 "fmt"
 "encoding/json"
)
type Host struct {
 Id interface{}
 IdcId interface{}
}
func main() {
 b := []byte(`{"ID": 11, "IDCid": "1001"}`)
 m := Host{}
 err := (b, &m)
 if err != nil {
 ("Umarshal failed:", err)
 return
 }
 ("m:%#v\n", m)
}

output:

m:{Id:11, IdcId:”1001”}}

Supplement: There are fields of uncertain types in the gin bindJSON structure

There are fields of uncertain types in the structure. Use interface{}, and then BindJSON will automatically store the corresponding type according to the input, for example

type student struct {
 Name string   `json:"name"`
 Info interface{} `json:"info"`
}

For example, the input of info

enter

type

12

float64

“str”

string

{"str":"value"}

map[string]interface {}

true

bool

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.