检测JSON字符串Golang中的重复项 [英] detect duplicate in JSON String Golang

查看:461
本文介绍了检测JSON字符串Golang中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有JSON字符串

"{\"a\": \"b\", \"a\":true,\"c\":[\"field_3 string 1\",\"field3 string2\"]}"

如何使用Golang检测此json字符串中的重复属性

how to detect the duplicate attribute in this json string using Golang

推荐答案

使用 json.Decoder 遍历JSON.找到对象后,遍历键和值以检查重复的键.

Use the json.Decoder to walk through the JSON. When an object is found, walk through keys and values checking for duplicate keys.

func check(d *json.Decoder, path []string) error {
    // Get next token from JSON
    t, err := d.Token()
    if err != nil {
        return err
    }

    delim, ok := t.(json.Delim)

    // There's nothing to do for simple values (strings, numbers, bool, nil)
    if !ok {
        return nil
    }

    switch delim {
    case '{':
        keys := make(map[string]bool)
        for d.More() {
            // Get field key
            t, err := d.Token()
            if err != nil {
                return err
            }
            key := t.(string)

            // Check for duplicates
            if keys[key] {
                fmt.Printf("Duplicate %s\n", strings.Join(append(path, key), "/"))
            }
            keys[key] = true

            // Check value
            if err := check(d, append(path, key)); err != nil {
                return err
            }
        }
        // Consume trailing }
        if _, err := d.Token(); err != nil {
            return err
        }

    case '[':
        i := 0
        for d.More() {
            if err := check(d, append(path, strconv.Itoa(i))); err != nil {
                return err
            }
            i++
        }
        // Consume trailing ]
        if _, err := d.Token(); err != nil {
            return err
        }

    }
    return nil
}

这里是怎么称呼它:

data := `{"a": "b", "a":true,"c":["field_3 string 1","field3 string2"], "d": {"e": 1, "e": 2}}`
if err := check(json.NewDecoder(strings.NewReader(data)), nil); err != nil {
    log.Fatal(err)
}

输出为:

Duplicate a
Duplicate d/e

在操场上运行

这篇关于检测JSON字符串Golang中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆