解析一个比较异常的json,json中的key包含变量
{
"protocols": {
"80-0": {
"columns": [[[{
"name": "switch_1",
"desc": "开关量1",
"mode": "SLOT",
"type": "INT",
"block": "0",
"slot": "2",
"offset": "7",
"start": "7",
"stride": "2"
}, {
"name": "switch_2",
"desc": "开关量2",
"mode": "SLOT",
"type": "INT",
"block": "0",
"slot": "3",
"offset": "9",
"start": "9",
"stride": "2"
},
]]],
},
"80-1":{
"columns": [[[{
"name": "switch_1",
"desc": "开关量1",
"mode": "SLOT",
"type": "INT",
"block": "0",
"slot": "2",
"offset": "10",
"start": "10",
"stride": "2"
}, {
"name": "switch_2",
"desc": "开关量2",
"mode": "SLOT",
"type": "INT",
"block": "0",
"slot": "3",
"offset": "12",
"start": "12",
"stride": "2"
},
解析如下,主要为需要将包含变量的key,解析为一个map[string]...
var ostype = runtime.GOOS
type Protocolstmp struct {
Protocols map[string]Columns `json:protocols`
}
type Columns struct {
Columns [][][]CDColumn `json:cloumns`
}
type CDColumn struct {
Name string `json:name`
desc string `json:desc`
Mode string `json:columns`
Type string `json:type`
Block string `json:columns`
Slot string `json:slot`
Offset string `json:offset`
Start string `json:start`
Stride string `json:stride`
}
func GetProtocol (id string, columnkey string) (CDColumn, error) {
localpath, _ := os.Getwd()
var filename string
if ostype == "windows" {
filename = filepath.Join(localpath, "config\\genProtocol.json")
} else {
filename = filepath.Join(localpath, "config/genProtocol.json")
}
fmt.Println(filename)
data, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Println(err)
}
tmp1 := Protocolstmp{}
json.Unmarshal(data, &tmp1)
for _, pp := range tmp1.Protocols[id].Columns[0] {
//fmt.Printf("查询到协议:%+v\n", pp)
for _, i := range pp {
if i.Name == columnkey {
fmt.Printf("查询到上报字段的信息:%+v\n", i)
return i, nil
}
}
}
return CDColumn{}, errors.New("Not found")
}
网友评论