Add root element to existing Json in Go lang

Viewed 54

I'm trying to add string "Employee" to my existing JSON response. Also, we need to be able to generate this version of json based on an user condition. Only if the user condition is met, I need to generate second version of json with string "Employee" added. If not the first version without string "Employee" should be generated. How can I achieve it with out updating the existing struct and how can I check this with if clause to check for the condition and then generate json based on it?

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
         }
      }
   ]
}
3 Answers

Considering you're just wrapping it it an outer object, I don't see any reason you'd need to change the existing struct, just wrap it in a new one. I'll have to make some guesses/assumptions here since you've only shown the JSON and not the Go code that produces it, but assuming your existing JSON is produced by marshaling something like var response []Employee, the desired JSON could be produced in your condition by marshaling instead:

json.Marshal(struct{Employee []Employee}{response})

Working example: https://go.dev/play/p/vwDvxnQ96G_2

Use string concatenation:

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

Run an example on the GoLang playground.

Here's the code if you are working with []byte instead of string:

func addRoot(json []byte) []byte {
    const prefix = `{ "Employee":`
    const suffix = `}`
    result := make([]byte, 0, len(prefix)+len(json)+len(suffix))
    return append(append(append(result, prefix...), json...), suffix...)
}

Run this example on the GoLang playground.

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)

Related