Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 如何在拆分后将数组转换为嵌套json对象_Go - Fatal编程技术网

Go 如何在拆分后将数组转换为嵌套json对象

Go 如何在拆分后将数组转换为嵌套json对象,go,Go,我试图处理来自的一些错误描述,因为我需要它们是嵌套的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 'emai

我试图处理来自的一些错误描述,因为我需要它们是嵌套的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]]

有什么线索可以告诉我如何做到这一点吗?

?这很有魅力!如果您将其作为答案发布,我将接受。这是因为
appendtoMap
不是映射,而是映射的字符串值
resultmaperors
感谢您的输入!
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))