跳至主要内容

JSON 转 Go 结构体

将 JSON 转换为带 json 标签的 Go 结构体,按 gofmt 方式对齐。可选字段会变成带 omitempty 的指针;时间戳可转换为 time.Time。

100% 客户端 · 没有数据离开您的浏览器

*string tells “missing or null” apart from “”

Off uses int

RFC 3339 strings like 2026-03-14T09:26:53Z

Go — 3 types
package main

import "time"

type Root struct {
	ID        int64     `json:"id"`
	Username  string    `json:"username"`
	Email     string    `json:"email"`
	IsActive  bool      `json:"isActive"`
	Rating    float64   `json:"rating"`
	CreatedAt time.Time `json:"createdAt"`
	AvatarURL any       `json:"avatarUrl"`
	Tags      []string  `json:"tags"`
	Address   Address   `json:"address"`
	Orders    []Order   `json:"orders"`
}

type Address struct {
	Street  string `json:"street"`
	City    string `json:"city"`
	ZipCode string `json:"zipCode"`
}

type Order struct {
	OrderID string  `json:"orderId"`
	Total   float64 `json:"total"`
	Items   int64   `json:"items"`
	Shipped bool    `json:"shipped"`
	Coupon  *string `json:"coupon,omitempty"`
}

Arrays of objects are merged: a key missing from some items becomes optional, null makes a field nullable, and identical shapes share one type. Paste several examples in an array for the most accurate types.

关于此工具

粘贴 JSON,即可得到可直接放入代码的 Go 结构体。字段名遵循 Go 命名约定,使用 ID、URL 和 API 等首字母缩略词,每个字段都带有 json 标签,输出的对齐方式与 gofmt 格式化后完全一致。对象数组会被合并,因此在某些项中缺失的键会变成可选字段(带 omitempty 的指针),null 会使字段可为空,即使是 10.0 这样的值也能区分整数和小数。嵌套对象会成为独立的命名类型,结构相同的对象共用一个类型,以 ID 为键的对象会变成 map。您可以通过选项设置包名、指针、omitempty、int 或 int64,以及将 RFC 3339 时间戳转换为 time.Time。您还可以在同一页面切换到 Rust、C#、Python 或 Kotlin。

如何将 JSON 转换为 Go 结构体

根据 JSON 示例生成 Go 类型。

  1. 1

    粘贴 JSON

    粘贴一个 JSON 对象;若要获得最准确的类型,请粘贴一个示例数组。

  2. 2

    选择选项

    设置根类型名称、包名、指针、omitempty 和 time.Time。

  3. 3

    复制代码

    复制结构体或下载 types.go。