簡體   English   中英

如何在 Go 的結構中打印出 JSON 的特定部分?

[英]How can I print out a specific part of my JSON within a struct in Go?

我想打印出 Go 結構中的 JSON 的第一“行”。 JSON 看起來像

[
   {
      "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"
   }
]

我把它放在這樣的結構中

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);
}

然后我可以使用

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

我希望能夠打印出與特定 ID 對齊的 JSON。 例如,我希望能夠指定 7,然后 id:7 JSON 行中的所有內容都將以上述格式打印出來。 所以它應該打印出來:

7 user
subject
message

我怎樣才能做到這一點?

如果要打印“第一個”項目。 然后你當然可以使用項目的索引來做到這一點。

fmt.Println(information[0])

如果要打印特定項目,則必須使用范圍進行迭代並檢查該項目是否符合條件。

構建項目的 map 可能更有幫助,在這種情況下使用 ID 作為鍵。

// 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)

您還可以在 Info 上添加一個方法來包含格式化邏輯。

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

然后簡單地調用它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM