代码之家  ›  专栏  ›  技术社区  ›  P. Nick

如何将数组拆分成嵌套的json对象

go
  •  -2
  • P. Nick  · 技术社区  · 6 年前

    我正试图处理来自 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 回复  |  直到 6 年前
        1
  •  1
  •   mkopriva    6 年前
    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))