首頁 >後端開發 >Golang >如何在 Go 中將動態 JSON 鍵解組到結構欄位?

如何在 Go 中將動態 JSON 鍵解組到結構欄位?

Patricia Arquette
Patricia Arquette原創
2024-11-19 01:26:02978瀏覽

How to Unmarshal Dynamic JSON Keys into Struct Fields in Go?

將動態JSON 鍵解組到Go 中的結構體欄位

動態JSON 鍵在解組到具有靜態欄位名稱的結構時可能會帶來挑戰。考慮以下JSON 設定檔:

{
  "things" :{
    "123abc" :{
      "key1": "anything",
      "key2" : "more"
    },
    "456xyz" :{
      "key1": "anything2",
      "key2" : "more2"
    },
    "blah" :{
      "key1": "anything3",
      "key2" : "more3"
    }
  }
}

要在Go 結構中表示此JSON,您可以使用映射而不是靜態欄位名稱:

type X struct {
    Things map[string]Thing
}

type Thing struct {
    Key1 string
    Key2 string
}

然後,解組JSON使用json .Unmarshal 函數:

var x X
if err := json.Unmarshal(data, &x); err != nil {
    // handle error
}

透過這種方法,動態鍵成為映射的鍵,允許您可以根據需要存取值。

但是,如果鍵必須是Thing 結構體的成員,您可以編寫一個循環來在解組後面添加鍵:

type Thing struct {
    Name string `json:"-"` // add the field
    Key1 string
    Key2 string
}

...

// Fix the name field after unmarshal
for k, t := range x.Things {
    t.Name = k
    x.Things[k] = t
}

This方法允許您同時擁有作為字段的鍵和動態值。

以上是如何在 Go 中將動態 JSON 鍵解組到結構欄位?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn