我正在接收此结构,并且不知道如何创建go结构以将其编组为:
[
{
“searchinfo”:[
{
“PrefProv”:“68”,
“语言”:“乌兹别克语”
}
]
}
]
如何定义将其解组的go结构?
最佳答案
这里是一个例子:
package main
import (
"encoding/json"
"fmt"
)
type RawStruct []struct {
Searchinfo []struct {
PrefProv string `json:"PrefProv"`
Language string `json:"Language"`
} `json:"searchinfo"`
}
func main() {
raw_data := `[{"searchinfo":[{"PrefProv":"68","Language":"Uzbek"}]}]`
var rawStruct RawStruct
if err := json.Unmarshal([]byte(raw_data), &rawStruct); err != nil {
panic(err.Error())
}
fmt.Printf("%+v\n", rawStruct)
fmt.Println("---------")
for indexStruct, itemStruct := range rawStruct {
fmt.Printf("Iterating element [%d] of itemStruct: [%+v]\n", indexStruct, itemStruct)
for indexInfo, itemInfo := range itemStruct.Searchinfo {
fmt.Printf("[%d] PrefProv: %s\n", indexInfo, itemInfo.PrefProv)
fmt.Printf("[%d] Language: %s\n", indexInfo, itemInfo.Language)
}
}
}
结果:
[{Searchinfo:[{PrefProv:68 Language:Uzbek}]}]
---------
Iterating element [0] of itemStruct: [{Searchinfo:[{PrefProv:68 Language:Uzbek}]}]
[0] PrefProv: 68
[0] Language: Uzbek