-2

I want to print out the first "row" of my JSON that is within a struct in Go. The JSON looks like

[
   {
      "id":"7",
      "username":"user",
      "subject":"subject",
      "message":"message"
   },
   {
      "id":"6",
      "username":"user2",
      "subject":"subject2",
      "message":"message2"
   },
   {
      "id":"5",
      "username":"user3",
      "subject":"subject3",
      "message":"message3"
   },
   {
      "id":"4",
      "username":"user4",
      "subject":"subject4",
      "message":"message4"
   },
   {
      "id":"3",
      "username":"user5",
      "subject":"subject5",
      "message":"message5"
   },
   {
      "id":"2",
      "username":"user6",
      "subject":"subject6",
      "message":"message6"
   },
   {
      "id":"1",
      "username":"user7",
      "subject":"subject7",
      "message":"message7"
   }
]

I have put it in a Struct like this

type Info struct {
    Id string
    Username string
    Subject string
    Message string
}
infoJson := html;
var information []Info;
err2 := json.Unmarshal([]byte(infoJson), &information);
if err2 != nil {
    fmt.Println(err2);
}

And then I can print all of them out using

for _, info := range information {
    fmt.Println(info.Id + " " + info.Username);
    fmt.Println(info.Subject);
    fmt.Println(info.Message);
}

I would like to just be able to print out the JSON that is aligned with a specific id. For example, I wish to be able to specify 7 and then all the things that are in the id:7 JSON row will be printed out in the above format. So it should print out:

7 user
subject
message

How can I do this?

erik258
  • 14,701
  • 2
  • 25
  • 31
  • 4
    `if info.Id != 7 { continue }` – Peter Dec 18 '21 at 19:01
  • 1
    I often create a dictionary using something like map[int]Info. Or use string as key if you know it's unique. So instead of appending to a slice you insert into the map. And then no loop required to get the element or check if exists – Brian Wagner Dec 18 '21 at 20:52

1 Answers1

0

If you want to print the "first" item. Then you can certainly use the index of the item to do that.

fmt.Println(information[0])

If you want to print a specific item, then you would have to iterate using range and check if the item matches the condition.

It may be more helpful to build a map of the items, in this case using ID as the key.

// Print the first item.
fmt.Println(information[0])

// Create a map to index items by ID.
dictionary := make(map[string]Info)
for _, info := range information {
    dictionary[info.Id] = info
}

element, ok := dictionary["7"]
if !ok {
    fmt.Println("Not found.")
    return
}
fmt.Println(element)

You can also add a method on Info to contain the formatting logic.

func (i *Info) Print() string {
    return fmt.Sprintf("%s %s\n%s\n%s\n", i.Id, i.Username, i.Subject, i.Message)
}

And then simply call that:

// Print the first item.
fmt.Println(information[0].Print())
Brian Wagner
  • 817
  • 1
  • 6
  • 11