Home > Software engineering >  Printing nested fields on Go objects
Printing nested fields on Go objects

Time:11-25

I'm trying to understand from the below code, how can I print only "species" and "width" key values.

package main

import (
    "encoding/json"
    "fmt"
)

type Dimensions struct {
    Height int
    Width  int
}

type Bird struct {
    Species     string
    Description string
    Dimensions  Dimensions
}

func main() {
    birdJson := `{"species":"pigeon","description":"likes to perch on rocks", "dimensions":{"height":24,"width":10}}`
    var bird Bird
    json.Unmarshal([]byte(birdJson), &bird)
    fmt.Println(bird)
    // {pigeon likes to perch on rocks {24 10}}
}

The output I'm expecting is: pigeon and 10

CodePudding user response:

What you're doing here is printing the entire object when you should be printing the specific fields you're looking for. Instead, you should try this:

fmt.Println(bird.Species, bird.Dimensions.Width)

which will yield:

pigeon 10

To make this a bit more readable, you can use fmt.Printf like so:

fmt.Printf("Species: %s, Width: %d\n", bird.Species, bird.Dimensions.Width)

which will yeild:

Species: pigeon, Width: 10

CodePudding user response:

You can put a json tag on the structure that does not need to be printed, like this json: "-"

  •  Tags:  
  • go
  • Related