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

Time:10-10

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.

CodePudding user response:

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.

CodePudding user response:

You can use a pointer, then check against nil:

package main

import (
   "encoding/json"
   "fmt"
)

var input = []byte(`
[
  {"name" : "name1", "mobile": "123", "email": "[email protected]", "carrier": "carrier1", "city": "city1"},
  {"name" : "name2", "mobile": "1234", "carrier": "carrier2", "city": "city2"}
]
`)

type contact struct {
   Name string
   Email *string
}

func main() {
   var contacts []contact
   json.Unmarshal(input, &contacts)
   // [{Name:name1 Email:0xc00004a340} {Name:name2 Email:<nil>}]
   fmt.Printf("% v\n", contacts)
}
  • Related