英文:
Merging two JSON strings in golang
问题
我有一个结构体,我以传统的方式将其转换为JSON:
type Output struct {
Name string `json:"name"`
Command string `json:"command"`
Status int `json:"status"`
Output string `json:"output"`
Ttl int `json:"ttl,omitempty"`
Source string `json:"source,omitempty"`
Handlers []string `json:"handlers,omitempty"`
}
sensu_values := &Output{
Name: name,
Command: command,
Status: status,
Output: output,
Ttl: ttl,
Source: source,
Handlers: handlers,
}
我想从文件系统中读取任意的JSON文件,用户可以定义该文件的内容,然后将其添加到现有的JSON字符串中,保留原始字符串中的重复部分。
你可以如何实现这个功能?
英文:
I have a struct which I convert to JSON in the old fashioned way:
type Output struct {
Name string `json:"name"`
Command string `json:"command"`
Status int `json:"status"`
Output string `json:"output"`
Ttl int `json:"ttl,omitempty"`
Source string `json:"source,omitempty"`
Handlers []string `json:"handlers,omitempty"`
}
sensu_values := &Output{
Name: name,
Command: command,
Status: status,
Output: output,
Ttl: ttl,
Source: source,
Handlers: [handlers],
}
I want to read an arbitrary JSON file from the filesystem, which can be defined as anything by the user, and then add it to the existing JSON string, taking the duplicates from the original.
How can I do this?
答案1
得分: 12
{
"environment": "production",
"runbook": "http://url",
"message": "there is a problem"
}
最好在将输入的 JSON 反序列化之后,将两个结构体合并,然后再将其序列化为 Output
结构体。
示例代码:
inputJSON := {"environment": "production", "runbook":"http://url","message":"there is a problem"}
out := map[string]interface{}{}
json.Unmarshal([]byte(inputJSON), &out)
out["name"] = sensu_values.Name
out["command"] = sensu_values.Command
out["status"] = sensu_values.Status
outputJSON, _ := json.Marshal(out)
英文:
Input JSON :
{
"environment": "production",
"runbook": "http://url",
"message": "there is a problem"
}
It's better to unmarshal the input JSON and combine the two structures before marshaling Output
struct.
Sample Code
inputJSON := `{"environment": "production", "runbook":"http://url","message":"there is a problem"}`
out := map[string]interface{}{}
json.Unmarshal([]byte(inputJSON), &out)
out["name"] = sensu_values.Name
out["command"] = sensu_values.Command
out["status"] = sensu_values.Status
outputJSON, _ := json.Marshal(out)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论