When sweeping, check if the JSON object has multiple values ​​of the same key

I am trying to see if the .json file has several identical keys

"gauge1":{
    "name":"someName",
    "name":"someName1"
}

is there any way to check if a key is used 'name'in json more than once? If you cancel a json file with several keys with the same name, it will overwrite the previously written key, and gauge1.namewillsomeName1

Any help would be greatly appreciated!

+4
source share
2 answers

You can create a string type json.Unmarshalerthat returns an error if it is assigned more than once during unwinding.

type singleAssignString string

func (s *singleAssignString) UnmarshalJSON(b []byte) error {
    if s != nil && *s != "" {
        return fmt.Errorf("multiple string assignment")
    }

    *s = singleAssignString(string(b))
    return nil
}

https://play.golang.org/p/v4L1EjTESX

json.Decoder, , . UnmarshalJSON. :

type Data struct {
    Name string
}

func (d *Data) UnmarshalJSON(b []byte) error {
    dec := json.NewDecoder(bytes.NewReader(b))

    key := ""
    value := ""

    for dec.More() {
        tok, err := dec.Token()
        if err != nil {
            return err
        }

        s, ok := tok.(string)
        if !ok {
            continue
        }

        switch {
        case key == "":
            key = s
            continue
        case value == "":
            value = s
        }

        if key == "Name" {
            if d.Name != "" {
                return fmt.Errorf("multiple assignment to Name")
            }
            d.Name = s
        }

        key = ""

    }
    return nil
}
+3

encoding/json, Decoder, Token() JSON.

( ), , , JSON.

+1

Source: https://habr.com/ru/post/1649454/


All Articles