go - 如何向 map[string]interface{} 添加新值
问题描述
我想为map[string]interface{}
.
m := map[string]interface{}{}
for _, r := range a.RouteSettings {
m[r.FunctionName] = map[string]interface{}{
"handler": a.HandlerPath,
"name": a.Naming.LambdaFunctionName(r.FunctionName),
"events": []map[string]interface{}{
{
"http": map[string]interface{}{
"path": r.Path,
"method": strings.ToLower(r.Method),
"cors": true,
},
},
},
}
# here is the issue. I want to add new value.
if a.CognitoArn != "" {
m[r.FunctionName]["authorizer"] = map[string]interface{}{
"arn" : a.CognitoArn,
}
}
}
我希望它的工作结果是这样的:
m[r.FunctionName] = map[string]interface{}{
"handler": a.HandlerPath,
"name": a.Naming.LambdaFunctionName(r.FunctionName),
"events": []map[string]interface{}{
{
"http": map[string]interface{}{
"path": r.Path,
"method": strings.ToLower(r.Method),
"cors": true,
},
},
},
"authorizer" : map[string]interface{}{
"arn" : a.CognitoArn,
},
}
但它不起作用。
并发生编译错误。
请给出解决方案以增加现有的新价值map[string]interface{}
。
解决方案
因为m
is map[string]interface{}
,你必须断言m[r.FunctionName]
的实际类型来做任何有意义的事情:
m[r.FunctionName].(map[string]interface{})["authorizer"] = map[string]interface{}{
"arn" : a.CognitoArn,
}
但从长远来看,我宁愿花一些时间为这类数据设计结构类型。
推荐阅读
- python - 如果 foo else False 比 bool(foo) 快,为什么 True if foo else False?
- neo4j - 使用 CSV 文件在 Neo4j 上创建关系
- jsonschema - 验证器无法识别 oneOf 中的属性
- vue.js - vuejs chartjs问题,数组显示1个人的多个数据
- excel - Excel 中的条件 ISNUMBER 语句
- flutter - flutter_staggered_grid_view 中的图像未显示
- html - 多选的样式选项
- wordpress - 使用多个“orderby”对 wp_query 进行排序?
- google-sheets - 根据查找值对整个工作表应用条件格式
- c# - Razor 页面未关闭的图像标记