在Go语言中,向一个未知类型的映射(map)中添加键值对是可能的吗?

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

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

问题

我有多个具有不同格式的JSON文件。它们都包含一个包含映射的数组。然而,这些映射具有不同的结构。

a.json

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

b.json

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

内部映射的结构是无关紧要的。我只想向它们中的所有映射添加一个新的键值对,使它们看起来像这样:

a.json

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

b.json

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

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"} 
   } 
]

</details>


# 答案1
**得分**: 1

你可以使用一个 map 切片:
```go
var data []map[string]interface{}

你可以进行解析:

json.Unmarshal(jsonData, &data)

然后添加键值对:

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

当然,你需要进行必要的错误检查,并确保 data[i] 不为 nil。

英文:

You can use a slice of maps:

var data []map[string]interface{}

You can unmarshal:

json.Unmarshal(jsonData,&amp;data)

and then add the keys:

for i:=range data {
   data[i][&quot;new_key&quot;]=&quot;newValue&quot;
}

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

huangapple
  • 本文由 发表于 2021年5月20日 10:17:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/67613086.html
匿名

发表评论

匿名网友

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

确定