3 回答

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個(gè)贊
試試這個(gè),如果那適合你更好
package main
import (
"fmt"
)
func main() {
fmt.Printf("%#v\n",deviceSchemaJson)
}
var deviceSchemaJson = value{
"additionalProperties": false,
"properties": value{
"application": value{
"type": "string",
},
"hostname": value{
"type": "string",
},
"ipaddress": value{
"oneOf": []valuestring{{"format": "ipv4"}, {"format": "ipv6"}},
"type": "string",
},
"kernel_version": valuestring{
"type": "string",
},
},
"type": "object",
}
type value map[string]interface{}
type valuestring map[string]string
https://play.golang.org/p/6Kq5pvXYvNm

TA貢獻(xiàn)1793條經(jīng)驗(yàn) 獲得超6個(gè)贊
如何避免每次都定義?map[string]string
通過(guò)定義表示數(shù)據(jù)結(jié)構(gòu)的類型。
type DeviceSchema struct {
AdditionalProperties bool
Properties Properties
Type string
}
type Properties struct {
Application string
Hostname string
IpAddress []map[string]string
KernelVersion string
}
func main() {
deviceSchemaData := DeviceSchema{
AdditionalProperties: false,
Properties: Properties{
IpAddress: []map[string]string{{"format": "ipv4"},{"format": "ipv6"}},
},
Type: "object",
}
fmt.Println(deviceSchemaData)
}
https://play.golang.org/p/iHfoft1zyAn

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超4個(gè)贊
簡(jiǎn)化定義的一種方法是:
func stringMap(s...string) map[string]string {
ret:=map[string]string{}
for i:=0; i<len(s);i+=2 {
ret[s[i]]=s[i+1]
}
return ret
}
var deviceSchemaJson = map[string]interface{}{
"additionalProperties": false,
"properties": map[string]interface{}{
"application": stringMap("type","string"),
"hostname": stringMap("type","string"),
"ipaddress": map[string]interface{}{
"oneOf": []map[string]string{stringMap("format","ipv4"),stringMap("format","ipv6")},
"type": "string",
},
"kernel_version": stringMap("type","string"),
},
"type": "object",
}
- 3 回答
- 0 關(guān)注
- 120 瀏覽
添加回答
舉報(bào)