-1

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
clattenburg cake
  • 1,096
  • 3
  • 19
  • 40

1 Answers1

1

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.

thwd
  • 26
  • 2