Home > Software design >  How to get the number of items from a structure sub field using reflect in go
How to get the number of items from a structure sub field using reflect in go

Time:09-01

I have some issues when getting the number of items from a sub field in a slice struct through reflect package.

This is how I'm trying to get the number of items from Items

func main() {

  type Items struct {
      Name    string `json:"name"`
      Present bool   `json:"present"`
  }

  type someStuff struct {
      Fields string     `json:"fields"`
      Items    []Items `json:"items"`
  }

  type Stuff struct {
      Stuff []someStuff `json:"stuff"`
  }

  some_stuff := `{
                  "stuff": [
                     {
                       "fields": "example",
                       "items": [
                         { "name": "book01", "present": true },
                         { "name": "book02", "present": true },
                         { "name": "book03", "present": true }                                        
                       ]
                     }
                   ]
                }`

  var variable Stuff

  err := json.Unmarshal([]byte(some_stuff), &variable)
  if err != nil {
      panic(err)
  }

  //I want to get the number of items in my case 3
  NumItems := reflect.ValueOf(variable.Stuff.Items)

}

This is the error:

variable.Items undefined (type []Stuff has no field or method Items)

I'm unsure if I can retrieve the number of items like that.

CodePudding user response:

I have already fixed the issue.

In order to get the number of sub fields we can make use of Len() from reflect.ValueOf.

The code now is getting the number of Items:

package main

import (
    "encoding/json"
    "fmt"
    "reflect"
)

func main() {

    type Items struct {
        Name    string `json:"name"`
        Present bool   `json:"present"`
    }

    type someStuff struct {
        Fields string  `json:"fields"`
        Items  []Items `json:"items"`
    }

    type Stuff struct {
        Stuff []someStuff `json:"stuff"`
    }

    some_stuff := `{
                  "stuff": [
                     {
                       "fields": "example",
                       "items": [
                         { "name": "book01", "present": true },
                         { "name": "book02", "present": true },
                         { "name": "book03", "present": true }                                        
                       ]
                     }
                   ]
                }`

    var variable Stuff

    err := json.Unmarshal([]byte(some_stuff), &variable)
    if err != nil {
        panic(err)
    }

    //I want to get the number of items in my case 3
    t := reflect.ValueOf(variable.Stuff[0].Items)
    fmt.Println(t.Len())

}

Output: 3
  • Related