在golang中合并两个JSON字符串

时间:2016-11-08 16:04:21

标签: json go

我有一个结构,我以老式的方式转换为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字符串中,从原始文件中获取重复项。

我该怎么做?

1 个答案:

答案 0 :(得分:6)

输入JSON:

{
    "environment": "production",
    "runbook": "http://url",
    "message": "there is a problem"
}

最好在编组Output struct之前解组输入JSON并组合这两个结构。

示例代码

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)

Play Link

相关问题