在Go中解组时尝试捕获JSON中的重复属性

时间:2018-08-09 17:15:31

标签: json go unmarshalling

我正在尝试在Go应用程序中完成以下任务:

我想接收JSON字符串,并确保未在同一级别声明相同的属性。例如,像这样的东西:

{
   "name" : "Matias",
   "Age"  : 16,
   "Age"  : 31
}

将需要抛出一个我已经声明过 Age 的错误。关键是,在下面您可以看到我到目前为止已经达到的目标,当我将字符串解组后,我丢失了重复的属性。因此,在我要遍历的 map [string] interface {} 中,没有重复的字段,但是原始字符串中有文件要加载。

有人对我如何做到这一点有任何想法吗?

func catchDuplicates(unm_spec *interface{}) []models.Result {
    m := (*unm_spec).(map[string]interface{})
    already_seen := make(map[string]bool)

    for k, v := range m {
        if already_seen[k] == false {
            fmt.Println("It seems its the first time I see this : ", k , " ", already_seen[k] )
            already_seen[k] = true
        }else {
            fmt.Println("I got a duplicate here ", k , " ", already_seen[k] )
            results = append(results, models.Result{ 
                false,
                k,
                true,
                "This attribute was already declared",
                "no_dup error",
            })
        }
        switch vv := v.(type) {
        case string:
            //fmt.Println(k, "is string", vv)
        case float64:
            fmt.Println(k, "is float64", vv)
        case []interface{}:
            //fmt.Println(k, "is an array:")
        default:
            //fmt.Println(k, "is of a type I don't know how to handle")
        }
    }
    return results
}

0 个答案:

没有答案