Check if struct within struct exists

147 views Asked by At

I have a json feed, and am trying to check if a struct within a struct exists.

type feed struct {
    Video          struct {
        Name string      `json:"name"`
    }   
}

And here's the unmarshal process:

data:= &feed{}

err := json.Unmarshal([]byte(structuredData), data)
    if err != nil {
        return err
    }

In some cases, Video exists and in other cases, it doesn't. I would like to validate this in an if statement, something like if data.Video != nil but this doesn't seem to compile (I get invalid Operation). How do I check whether Video exists or not?

1

There are 1 answers

0
thwd On BEST ANSWER

If a valid video has a non-empty name, then use data.Video.Name != "" to check for a valid video.

If you want to detect whether the video object is included in the JSON or not, then declare the type with pointer to the struct:

type feed struct {
    Video          *struct {  // <-- note * on this line
        Name string      `json:"name"`
    }   
}

The JSON decoder allocates the inner struct only if the JSON document has a video object.

Check for the presence of the video object in the JSON document using data.Video != nil.