3 回答
TA贡献1805条经验 获得超10个赞
试试这个,如果那适合你更好
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贡献1793条经验 获得超6个赞
如何避免每次都定义?map[string]string
通过定义表示数据结构的类型。
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贡献1827条经验 获得超4个赞
简化定义的一种方法是:
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 关注
- 89 浏览
添加回答
举报