dongmu2517 2018-08-22 12:59
浏览 159
已采纳

拆分后如何将数组转换为嵌套的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 2018-08-22 13:16
    关注
    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))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python语言实验
  • ¥15 我每周要在投影仪优酷上自动连续播放112场电影,我每一周遥控操作一次投影仪,并使得电影永远不重复播放,请问怎样操作好呢?有那么多电影看吗?
  • ¥20 电脑重启停留在grub界面,引导出错需修复
  • ¥15 matlab透明图叠加
  • ¥50 基于stm32l4系列 使用blunrg-ms的ble gatt 创建 hid 服务失败
  • ¥150 计算DC/DC变换器平均模型中的参数mu
  • ¥25 C语言代码,大家帮帮我
  • ¥15 请问以下文字内容及对应编码是用了什么加密算法或压缩算法呢?
  • ¥50 关于#html5#的问题:H5页面用户手机返回的时候跳转到指定页面例如(语言-javascript)
  • ¥15 无法使用此凭据登录,因为你的域不可用,如何解决?(标签-Windows)