Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check desired json key (not value) exist in the parsed json response in golang

Tags:

json

parsing

go

lets say i have a json response like this, as you can see sometimes email exists sometimes not. now i need to check the email key exists or not and pretty print the json response accordingly. how can i do this?

[
  {"name" : "name1", "mobile": "123", "email": "[email protected]", "carrier": "carrier1", "city", "city1"},
  {"name" : "name2", "mobile": "1234", "carrier": "carrier2", "city", "city2"}
  ...
]

here i need to check the p.Email exists or not, if it exists assign the email value if not assign empty string

for i, p := range jsonbody.Data {
                        
                        a := p.Name
                        b := p.Phone[i].Mobile
                        c := p.INTaddress[i].Email  // here i need to check 
                        d := p.Phone[i].Carrier
                        e := p.Address[i].City
                          
                         ..........

}
                        

i tried searching but not found any answers for golang.

like image 671
Vinay Kumar Rasala Avatar asked Oct 15 '25 21:10

Vinay Kumar Rasala


1 Answers

here i need to check the p.Email exists or not, if it exists assign the email value if not assign empty string

Note that when you define the field as Email string and the incoming JSON provides no "email" entry then the Email field will remain an empty string, so you could simply use that as is. No additional checks necessary.

If you want to allow for null use Email *string and simply use an if condition to check against nil as suggested by 072's answer.

And when you need to differentiate between undefined/null/empty use a custom unmarshaler as suggested in the answer below:

type String struct {
    IsDefined bool
    Value     string
}

// This method will be automatically invoked by json.Unmarshal
// but only for values that were provided in the json, regardless
// of whether they were null or not.
func (s *String) UnmarshalJSON(d []byte) error {
    s.IsDefined = true
    if string(d) != "null" {
        return json.Unmarshal(d, &s.Value)
    }
    return nil
}

https://go.dev/play/p/gs9G4v32HWL

Then you can use the custom String instead of the builtin string for the fields that you need to check whether they were provided or not. And to do the checking, you'd obviously inspect the IsDefined field after the unmarshal happened.

like image 74
mkopriva Avatar answered Oct 17 '25 11:10

mkopriva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!