Home > Back-end >  Add root element to existing Json in Go lang
Add root element to existing Json in Go lang

Time:09-23

I'm trying to add string "Employee" to my existing JSON response. And I need to add this root element only the condition from user input parameter is met. How can I achieve it with out updating the existing struct?

Below is my existing json response in go

[
   {
      "EmpId":{
         "String":"ABCD",
         "Valid":true
      },
      "Department":{
         "Float64":0,
         "Valid":true
      }
   }
]

How can I get my json response like below with out changing existing struct based on input parameter?

{
   "Employee":[
      {
         "EmpId":{
            "String":"ABCD",
            "Valid":true
         },
         "Department":{
            "Float64":0,
            "Valid":true
         }
      }
   ]
}

CodePudding user response:

Use string concatenation:

func addRoot(json string) string {
    return `{ "Employee":`   json   `}`
}

Run an example on the GoLang playground.

CodePudding user response:

If you have some JSON in a byte slice ([]byte) then you can just add the outer element directly - e.g. (playground):

existingJSON := []byte(`[
      {
         "EmpId":{
            "String":"ABCD",
            "Valid":true
         },
         "Department":{
            "Float64":0,
            "Valid":true
         }
      }
   ]`)
b := bytes.NewBufferString(`{"Employee":`)
b.Write(existingJSON)
b.WriteString(`}`)
fmt.Println(string(b.Bytes()))

If this is not what you are looking for please add further details to your question (ideally your attempt as a minimal, reproducible, example)

  •  Tags:  
  • go
  • Related