I have a struct like this:

type MyStruct struct {
    Name  string `json:"name"`
    Age   int    `json:"age"`
    Email string `json:"email"`
} 

然后我有一些值(可以是默认值,这意味着我不需要更新这个值)作为HTTP请求数据输入.我注意到生成的JSON正文将始终包含所有三个字段(nameageemail),即使我不需要更新所有字段.这样地:

{
  "name":"Kevin",
  "age":10,
  "email":""
}

Is there a way to Marshal so that the JSON body contains not all fields with the same struct? Example:

{
  "name":"kevin"
}

推荐答案

您想要使用omitempty选项

type MyStruct struct {
    Name  string `json:"name,omitempty"`
    Age   int    `json:"age"`
    Email string `json:"email,omitempty"`
}

If you want Age to be optional as well you have to use a pointer, since the zero value of an int isn't really "empty"

type MyStruct struct {
    Name  string `json:"name,omitempty"`
    Age   *int   `json:"age,omitempty"`
    Email string `json:"email,omitempty"`
}

Json相关问答推荐

Google Page to JSON应用程序脚本出现CORS错误

Jolt需要将缺少的值设置为空并保持相同的位置

Postgres Select json数组并重新映射属性名称

给定一个包含两个数组的JSON输入文件,如何使用Jolt将一个数组中的每个元素与另一个数组组合在一起?

使用JQ将对象数组转换为平面数组

数据到jsonObject到数据到 struct 是可能的吗?

(Kotlin)com.google.gson.internal.LinkedTreeMap无法转换为com.example.phonetest2.model.HallData

使用动态语言jQuery:根据匹配模式提取与其他值匹配的值

如何在JQ中展平多维数组

jq - 将父键值提取为子元素旁边的逗号分隔值

shell解析json并循环输出组合变量

使用 Jolt 变换将平面 json 转换为具有多个数组的嵌套 Json

如何在 Go 中生成带有排序键的 JSON?

如何使用 CORS 实现 JavaScript Google Places API 请求

JSON extract\set 的 SQLite JSON1 示例

将json字符反序列化为枚举

Spring MVC控制器中的JSON参数

使用 jq 如何用其他名称替换键的名称

Microsoft.Net.Http 与 Microsoft.AspNet.WebApi.Client

YAML 将 5e-6 加载为字符串而不是数字