我希望使用"encoding/json"包封送在我的应用程序的一个导入包中声明的 struct .

例如:

type T struct {
    Foo int
}

因为是导入的,所以 struct 中所有可用(导出)字段都以大写字母开头.但我希望使用小写键名:

out, err := json.Marshal(&T{Foo: 42})

将导致

{"Foo":42}

but I wish to get

{"foo":42}

有没有可能以简单的方式解决这个问题?

推荐答案

Have a look at the docs for encoding/json.Marshal. It discusses using struct field tags to determine how the generated json is formatted.

For example:

type T struct {
    FieldA int    `json:"field_a"`
    FieldB string `json:"field_b,omitempty"`
}

This will generate JSON as follows:

{
    "field_a": 1234,
    "field_b": "foobar"
}

Json相关问答推荐

jq不会为空输入返回非零

服务器不返回JSON

将JSON输入子数组转换为字符串顺序列表输出

如何用JQ更改空/布尔/数字的 colored颜色 ?

如何使用模式注册中心创建从主题中取消本地化的ks qlDB表?

基于 JSON 字段的 Jolt 条件标志

NoneType 对象的 Python 类型错误

Oracle JSON 查询中的动态列列表

GitHub Pages无法正确显示我的项目

在 JOLT 中重新排列值

通过一个序列化器更新多个模型数据

在PowerShell中按时间戳过滤JSON

SyntaxError:Object.parse(本机)AngularJS中的意外标记o

按 JSON 数据类型 postgres 排序

将 PHP 结果数组转换为 JSON

有必要清理 JSON 吗?

Json.NET 是否缓存类型的序列化信息?

如何将有向无环图 (DAG) 存储为 JSON?

请求返回字节,我无法解码它们

使用 C# 调用 json