英文:
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,&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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论