Is it possible to add a key-value pair to a map of unknown type in Go?

901 Views Asked by At

I have multiple JSON files with different formats. All of them consist of an array which contain maps. The maps, however, have different structures.

a.json

[
   {
       "a": "b", 
       "c": ["d", "e"] 
   } 
]

b.json

[
   {
       "f": ["g", "h"], 
       "i": {"j": "k"} 
   } 
]

Thr structure of the internal maps is irrelevant. I just want to add a new key-value pair to all of them, so they look like this a.json

[
   {
       "new_key": "new_value", 
       "a": "b", 
       "c": ["d", "e"] 
   } 
]

b.json

[
   {
       "new_key": "new_value",
       "f": ["g", "h"], 
       "i": {"j": "k"} 
   } 
]
1

There are 1 best solutions below

0
On

You can use a slice of maps:

var data []map[string]interface{}

You can unmarshal:

json.Unmarshal(jsonData,&data)

and then add the keys:

for i:=range data {
   data[i]["new_key"]="newValue"
}

Of course, you have to do the necessary error checks, and make sure data[i] is not nil.