我在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的正确方法吗?
答案 0 :(得分:1)
答案只是何时封送该结构的问题。完整的代码如下。
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))