go - 拆分后如何将数组转换为嵌套的json对象
问题描述
我正在尝试处理该库中的一些错误描述,因为我需要它们是嵌套的 JSON 对象。
这些错误最初似乎是一个数组,如下所示:
["String length must be greater than or equal to 3","Does not match format 'email'"]
我还需要包含包含错误的字段名称:
["Field1: String length must be greater than or equal to 3","Email1: Does not match format 'email'"]
之后,我需要用冒号分割每个数组值,:
这样我就可以将字段名称和错误描述放在单独的变量中,例如slice[0]
和slice[1]
。
有了它,我想像这样制作一个嵌套的 JSON 对象:
{
"errors": {
"Field1": "String length must be greater than or equal to 3",
"Email1": "Does not match format 'email'"
}
}
这是我试图实现这一目标的方式:
var errors []string
for _, err := range result.Errors() {
// Append the errors into an array that we can use to split later
errors = append(errors, err.Field() + ":" + err.Description())
}
// Make the JSON map we want to append values to
resultMap := map[string]interface{}{
"errors": map[string]string {
"Field1": "",
"Email1": ""
},
}
// So we actually can use the index keys when appending
resultMapErrors, _ := resultMap["errors"].(map[string]string)
for _, split := range errors {
slice := strings.Split(split, ":")
for _, appendToMap := range resultMapErrors {
appendToMap[slice[0]] = slice[1] // append it like so?
}
}
finalErrors, _ := json.Marshal(resultMapErrors)
fmt.Println(string(finalErrors))
但这会引发错误
main.go:59:28: non-integer string index slice[0]
main.go:59:39: cannot assign to appendToMap[slice[0]]
任何线索我如何能做到这一点?
解决方案
var errors = make(map[string]string)
for _, err := range result.Errors() {
errors[err.Field()] = err.Description()
}
// Make the JSON map we want to append values to
resultMap := map[string]interface{}{
"errors": errors,
}
finalErrors, _ := json.Marshal(resultMap)
fmt.Println(string(finalErrors))
推荐阅读
- python - 如何在模板中使用带有静态的简单缩略图?
- amazon-web-services - 使用 AWS CLI 的 AWS SES ConfigurationSet 交付选项
- python - 在 Heroku 上部署 Django/VueJs 应用程序时,在此服务器上找不到请求的资源错误
- laravel - Laravel 验证规则在命令中的表单请求和验证器之间共享
- sql - 优化多个联合的查询
- oracle - OSB 无法处理队列中不存在的消息
- r - R - 使用 effect() 函数总结混合模型 (lmer) 估计的“数据”参数类型错误
- java - 将 3 和 5 的倍数相加直到 n
- python - 在新 Django 上更改哈希密码的最佳方法是什么?
- java - 182. JavaFX Hello World Program -- Try 3 -- java: cannot find symbol symbol: class GridPane location: class sample.Main