dongmu2517
dongmu2517
2018-08-22 12:59

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

已采纳

I'm trying to deal with some error descriptions from this library because I need them to be nested JSON objects.

The errors seem to be an array originally, like this:

["String length must be greater than or equal to 3","Does not match format 'email'"]

I needed that to also include the field name of the containing error:

["Field1: String length must be greater than or equal to 3","Email1: Does not match format 'email'"]

After that I need to split each array value by colon : so I can have the field name and error description in separate variables like slice[0] and slice[1].

With that I want to make a nested JSON object like so:

{
    "errors": {
        "Field1": "String length must be greater than or equal to 3",
        "Email1": "Does not match format 'email'"
    }
}

This is my way of trying to achieve this:

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

But this throws the errors

main.go:59:28: non-integer string index slice[0]
main.go:59:39: cannot assign to appendToMap[slice[0]]

Any clue how I can achieve this?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douqi3064 douqi3064 3年前
    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))
    
    点赞 评论 复制链接分享