当使用`json.Marshal`时,如何将嵌套结构的名称转换为小写?

huangapple go评论84阅读模式
英文:

How do I lowercase a nested struct name when using json.marshal?

问题

我正在暴露一个带有一些数据的 REST 端点。它是一个结构体,比如说:

type status struct {
    Config struct {
        Allow   bool `json:"allow"`
        Expired bool `json:"expired"`
    }
    Database struct {
        Healthy    bool  `json:"healthy"`
        WaitCount  int64 `json:"wait_count"`
    }
}

我使用 json 标签来表示在调用端点时结构字段应该如何显示。使用上述代码,我得到以下响应负载:

{
    "Config": {
        "allow": false,
        "expired": false
    },
    "Database": {
        "healthy": true,
        "wait_count": 1
    }
}

我希望 ConfigDatabase 的首字母小写,即 configdatabase。然而,在 Go 代码中将它们更改为小写意味着 encoding/json 包无法“看到”它们,因为它们没有在包范围之外导出。

如何将嵌套结构体在 JSON 响应负载中转换为小写?

英文:

I'm exposing a REST endpoint with some data. It's a struct, say:

type status struct {
	Config struct {
		Allow   bool `json:"allow"`
		Expired bool `json:"expired"`
	}
	Database struct {
		Healthy          bool   `json:"healthy"`
		WaitCount        int64  `json:"wait_count"`
	}
}

I'm using the json tag to denote how a struct field should look when calling the endpoint. Using the above, I'm getting the following payload as response:

{
	"Config": {
		"allow": false,
		"expired": false,
	},
	"Database": {
		"healthy": true,
		"wait_count": 1,
	},
}

I'd like for Config and Database to be lowercase, meaning config and database. However, changing them to that in the Go code means the "encoding/json" package cannot "see" them as they aren't exported outside of the package scope.

How do I lowercase the nested struct's in the json response payload?

答案1

得分: 6

嵌套结构是包含结构中的一个字段。像其他字段一样,为嵌套结构添加字段标签:

type status struct {
    Config struct {
        Allow   bool `json:"allow"`
        Expired bool `json:"expired"`
    } `json:"config"` // <-- 在这里添加标签 ...
    Database struct {
        Healthy    bool   `json:"healthy"`
        WaitCount  int64  `json:"wait_count"`
    } `json:"database"` // <-- ... 和这里
}
英文:

The nested struct is a field in the containing struct. Add a field tags as you did with the other fields:

type status struct {
    Config struct {
        Allow   bool `json:&quot;allow&quot;`
        Expired bool `json:&quot;expired&quot;`
    } `json:&quot;config&quot;` // &lt;-- add tag here ...
    Database struct {
        Healthy          bool   `json:&quot;healthy&quot;`
        WaitCount        int64  `json:&quot;wait_count&quot;`
    } `json:&quot;database&quot;` // &lt;-- ... and here
}

huangapple
  • 本文由 发表于 2021年11月9日 15:27:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/69894274.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定