跳到主要內容

語言橋梁:JSON To Go結構

使用 json-to-go 的移植版本根據 JSON 生成 Go struct 定義,並用 gofmt 格式化。鍵變為匯出的 CamelCase 欄位並帶 json:"..." 標籤;巢狀物件變為內聯匿名 struct,null 變為 any。

編寫用於 json.Unmarshal 第三方 REST API 響應的 struct。

適用場景

  • 編寫用於 json.Unmarshal 第三方 REST API 響應的 struct。
  • 根據示例資料快速搭建 Go HTTP handler 的請求和響應型別。

使用方法

  1. 將 JSON 物件或陣列貼上到左側編輯器。
  2. 檢視生成的 struct;根型別始終命名為 AutoGenerated。
  3. 複製到你的包中,重新命名型別;如需複用內聯 struct,可將其提取為命名型別。

JSON

{
  "id": 42,
  "user_name": "ada",
  "score": 9.5,
  "active": true,
  "deleted_at": null,
  "tags": ["go", "json"],
  "address": { "city": "Tokyo", "zip": "100-0001" }
}

Go struct

type AutoGenerated struct {
	ID        int      `json:"id"`
	UserName  string   `json:"user_name"`
	Score     float64  `json:"score"`
	Active    bool     `json:"active"`
	DeletedAt any      `json:"deleted_at"`
	Tags      []string `json:"tags"`
	Address   struct {
		City string `json:"city"`
		Zip  string `json:"zip"`
	} `json:"address"`
}

功能與限制

生成在瀏覽器中進行。沒有型別名、內聯或命名 struct、標籤方面的設定。

首字母縮略詞會全部大寫(id 變為 ID),snake_case 變為 CamelCase,原始鍵保留在 json 標籤中。

整數變為 int(較大時為 int64),小數變為 float64。null、空陣列和混合型別陣列變為 any 或 []any。

陣列中的物件結構不同時,部分物件缺少的鍵會加上 ,omitempty。

FAQ

能轉換根節點為陣列的 JSON 嗎?

可以。會生成 type AutoGenerated []struct{...},合併陣列中所有物件的欄位。

為什麼我的 null 欄位型別是 any?

null 值不攜帶型別資訊。請把 any 替換為 *string 或 *time.Time 這樣的指標,以保留對 nil 的支援。

會生成命名的巢狀 struct 嗎?

不會。巢狀物件是內聯匿名 struct。如需引用它們,請手動移到命名型別中。

規範與參考資料