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 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办