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

时间:2018-08-22 12:59:45

标签: go

我正在尝试处理this library中的一些错误描述,因为我需要将它们嵌套在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]]

有什么线索可以实现吗?

1 个答案:

答案 0 :(得分:1)

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))