json - 创建后将值附加到 JSON 结构

标签 json go marshalling

我在 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))

关于json - 创建后将值附加到 JSON 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51310468/

相关文章:

jaxb - 如何忽略父类中的 JAXB 注释属性?

java - JSON 数据格式

ios - if语句ios检查json参数

go - 为什么结构内存大小与我的期望不一致?

mongodb - 基于 GO 的 Mongo 聚合查询问题

C# 更正来自 C++ 的托管代码

json - 使用 Freemarker 评估具有空值的 JSon

Python requests.post() 返回 None

go - 如何在 Go 中有效地处理大型数据数组(超过 10MiB)?

c# - 如何调用 C# 委托(delegate)以从 native C 最简单的方式传递字符串数组?