当前位置: > > > > 创建后将值附加到 JSON 结构
创建后将值附加到 JSON 结构
来源:stackoverflow
2024-04-27 15:06:39
0浏览
收藏
Golang不知道大家是否熟悉?今天我将给大家介绍《创建后将值附加到 JSON 结构》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!
问题内容
我在 go 中创建了一个 json 结构。这是我创建结构并添加必要值的代码。
type passport struct{
messagetopic string `json:"message_topic"`
devicename string `json:"device_name"`
deviceschema string `json:"device_schema"`
deviceid string `json:"device_id"`
}
type sentdata struct{
passport passport `json:"passport"`
integrationresult string `json:"integration_result"`
actionlog []string `json:"action_log"`
}
response := sentdata{
passport: passport {
messagetopic: "handshake_reply",
devicename: sensorconfig.passport.devicename, //ignore
deviceschema: sensorconfig.passport.deviceschema, //ignore
deviceid: "",
},
integrationresult: "",
actionlog: []string{},
}
sensorreply, _ := json.marshal(response)
我希望能够将字符串元素添加到 actionlog 数组中。我这样做的方法是:
if sensorconfig.passport.interfaces.wifi != "true" && sensorconfig.passport.interfaces.wifi != "false" && sensorconfig.passport.interfaces.wifi != "unknown"{
fmt.println("wifi: incorrect option")
response.actionlog = append(response.actionlog, "wifi: incorrect option")
}
fmt.println(string(sensorreply))
这可以编译,但是当我打印出 sensorreply 时,我得到:
{"passport":{"message_topic":"handshake_reply","device_name":"My RPi","device_schema":"sensor/data","device_id":""},"integration_result":"","action_log":[]}
如您所见,action_log 字段为空。这是将值附加到 json 的正确方法吗?
解决方案
答案只是何时封送结构的问题。下面完成了代码。
if sensorConfig.Passport.Interfaces.Wifi != "true" && sensorConfig.Passport.Interfaces.Wifi != "false" && sensorConfig.Passport.Interfaces.Wifi != "unknown"{
fmt.Println("Wifi: incorrect option")
response.ActionLog = append(response.ActionLog, "Wifi: incorrect option")
}
sensorReply, err := json.Marshal(response)
if err != nil {
panic(err)
}
fmt.Println(string(sensorReply))
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持米云!更多关于Golang的相关知识,也可关注米云公众号。
