How to a JSON is contain in an array JSON objects in golang

113 views
Skip to first unread message

Van Fury

unread,
May 24, 2021, 11:44:34 AM5/24/21
to golang-nuts
Hi,

I have an array of JSON objects as

Structs:
```
type Data struct {
    TaiList []Tai `json:"taiList"`
}

type Tai struct {
    PlmnId *PlmnId `json:"plmnId"`

    Tac string `json:"tac"`

    Nid string `json:"nid"`
}

type PlmnId struct {
    Mcc string `json:"mcc"`

    Mnc string `json:"mnc"`
}
```

The JSON is of the form

```
{
    "taiList": [
      {
        "plmnId": {
            "mcc": "244",
            "mnc": "24"
        },
        "tac": "00001",
        "nid": "99"
        },
        {
        "plmnId": {
            "mcc": "244",
            "mnc": "34"
        },
        "tac": "00001",
        "nid": "555"
        }
    ]
}
```

I would like to check if the JSON object "ta" is contain in the "taiList".

```
 var ta = model.Tai{
    PlmnId: &model.PlmnId{Mcc: "244", Mnc: "34"},
    Tac:    "00001",
    Nid:    "555",
}
```


I tried with the code below

```
func CheckTai(tai model.Tai, TaiList []model.Tai) bool {
    for _, Tai := range TaiList {
        if reflect.DeepEqual(Tai, tai) {
            return true
        }
    }
    return false
}

```

but CheckTai function return false.
The CheckTai only return true when there is only one JSON object that match the list as

```
{
      "taiList": [
        {
          "plmnId": {
            "mcc": "244",
            "mnc": "24"
          },
          "tac": "00001",
          "nid": "555"
        }

      ]
    }
```

Need help or idea on how to perform this check.

Neal McConachie

unread,
May 24, 2021, 11:58:31 PM5/24/21
to golang-nuts
The first recommendation I have is to make yourself a set of tests.  

In terms of this specific problem, it is likely because you're comparing pointers.
Here is an alternate approach that doesn't use reflection, and deals with the pointers as well:


I'd recommend you expand the tests to make sure you're happy with situations where the PmnId property is not given.

(Please excuse the formatting - I'm on my phone).

Van Fury

unread,
May 25, 2021, 4:32:29 AM5/25/21
to golang-nuts
Hi,

Thanks for the help.

BR
Abraham
Reply all
Reply to author
Forward
0 new messages