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

标签 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]]

有什么线索可以实现吗?

最佳答案

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

关于go - 拆分后如何将数组转换为嵌套的json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51967482/

相关文章:

asynchronous - go中如何实现异步读取?

dictionary - 遍历包含不同级别 map 的界面 map

go - 如何卡住具有依赖关系的微版本?

string - 如何使用字段的 String() 打印结构?

go - 您如何解决azure-storage-blob-go中的“验证失败:字段” body”不存在”错误?

algorithm - 霍尔的分区方案golang

go - 有没有一种断言类型的通用方法?

go - 在 RethinkDB 的 Do-function 中更新对象

go - 如何根据日期过滤集合并将其分配给 map

go - 为什么 fmt.Scanf 无法将小写字母读取为字节值?