Home > database >  Accessing Data in Nested []struct
Accessing Data in Nested []struct

Time:02-10

I'm working on unmarshaling some nested json data that I have already written a struct for. I've used a tool that will generate a struct based off json data, but am a bit confused how to work with accessing nested json data (and fields can sometimes be emtpy).

Here is an example of struct:

type SomeJson struct {
status         string `json:"status"`
message        string `json:"message"`
someMoreData []struct {
    constant bool `json:"constant,omitempty"`
    inputs   []struct {
        name string `json:"name"`
        type string `json:"type"`
    } `json:"inputs,omitempty"`
    Name    string `json:"name,omitempty"`
    Outputs []struct {
        Name string `json:"name"`
        Type string `json:"type"`
    } `json:"outputs,omitempty"`

I'm able to unmarshal the json data and access the top level fields (such as status and message), but am having trouble accessing any data under the someMoreData field. I understand this field is a (I assume an unknown) map of structs, but only have experience working with basic single level json blobs.

For reference this is the code I have to unmarshal the json and am able to access the top level fields.

someData := someJson{}
json.Unmarshal(body, &someData)

So what is exactly the best to access some nested fields such as inputs.name or outputs.name?

CodePudding user response:

to iterate over your particular struct you can use:

for _, md := range someData.someMoreData {
    println(md.Name)
    for _, out := range md.Outputs {
        println(out.Name, out.Type)
    }
}

to access specific field:

someData.someMoreData[0].Outputs[0].Name

CodePudding user response:

Couple of things to note:

  1. The struct definition is syntactically incorrect. There are couple of closing braces missing.
  2. type is a keyword.
  3. The status and message and other fields with lower case first letter fields are unexported. So, the Json parser will not throw error, but you will get zero values as output. Not sure that's what you observed.
  4. someMoreData is an array of structs not map.
  • Related