Merging two JSON strings in golang

huangapple go评论91阅读模式
英文:

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)

Play 链接

英文:

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)

Play Link

huangapple
  • 本文由 发表于 2016年11月9日 00:04:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/40491438.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定