1 回答
TA贡献1887条经验 获得超5个赞
去map[string]interface{}存储节点数据。对于带有动态键的未知 json 数据,接口是最好的,它将帮助您存储任何类型的数据。
package main
import (
"fmt"
"encoding/json"
)
type MyJsonName struct {
LatestHeight int `json:"latest_height"`
Timestamp int `json:"timestamp"`
TotalNodes int `json:"total_nodes"`
Nodes map[string]interface{}
}
var byteValue string = `{
"timestamp": 1533397325,
"total_nodes": 9522,
"latest_height": 535196,
"nodes": {
"220.75.229.130:3927": [
70015,
"/Satoshi:0.13.2/",
1530858117,
13,
165277,
"220.75.229.130",
"Seoul",
"KR",
37.5985,
126.9783,
"Asia/Seoul",
"AS4766",
"Korea Telecom"
],
"192.162.102.68:8333": [
70015,
"/Satoshi:0.15.1/",
1533061934,
13,
535196,
"192.162.102.68",
null,
"RU",
55.7386,
37.6068,
null,
"AS50113",
"MediaServicePlus LLC"
]
}
}`
func main() {
var MyJSONANE MyJsonName
err := json.Unmarshal([]byte(byteValue), &MyJSONANE)
if err != nil {
fmt.Println(err)
}
fmt.Printf("%+v",MyJSONANE)
}
Go 操场上的工作代码
要从 中获取基础值interface{},您需要对每种类型进行类型断言。您可以使用 switch 递归地从接口获取值。
func fetchValue(value interface{}) {
switch value.(type) {
case string:
fmt.Printf("%v is an string \n ", value.(string))
case bool:
fmt.Printf("%v is bool \n ", value.(bool))
case float64:
fmt.Printf("%v is float64 \n ", value.(float64))
case []interface{}:
fmt.Printf("%v is a slice of interface \n ", value)
for _, v := range value.([]interface{}) {
fetchValue(v)
}
case map[string]interface{}:
fmt.Printf("%v is a map \n ", value)
for _, v := range value.(map[string]interface{}) {
fetchValue(v)
}
default:
fmt.Printf("%v is unknown \n ", value)
}
}
- 1 回答
- 0 关注
- 196 浏览
添加回答
举报