如何在Go中解析JSON时指定默认值 [英] How to specify default values when parsing JSON in Go

查看:2887
本文介绍了如何在Go中解析JSON时指定默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Go中解析一个JSON对象,但想为未给出的字段指定默认值。例如,我有struct类型:

I want to parse a JSON object in Go, but want to specify default values for fields that are not given. For example, I have the struct type:

type Test struct {
    A string
    B string
    C string
}

A,B和C的默认值,分别是a,b和c。这意味着当我解析json的时候:

The default values for A, B, and C, are "a", "b", and "c" respectively. This means that when I parse the json:

{"A": "1", "C": 3}

我想得到结构:

I want to get the struct:

Test{A: "1", B: "b", C: "3"}

这可能使用内置程序包 encoding / json ?否则,是否有任何Go库具有此功能?

Is this possible using the built-in package encoding/json? Otherwise, is there any Go library that has this functionality?

推荐答案

这可以使用encoding / json:调用 json.Unmarshal ,你不需要给它一个空的结构,你可以给它一个默认值。

This is possible using encoding/json: when calling json.Unmarshal, you do not need to give it an empty struct, you can give it one with default values.

你的例子:

For your example:

var example []byte = []byte(`{"A": "1", "C": "3"}`)

out := Test{
    A: "default a",
    B: "default b",
    // default for C will be "", the empty value for a string
}
err := json.Unmarshal(example, &out) // <--
if err != nil {
    panic(err)
}
fmt.Printf("%+v", out)



在Go playground中运行此示例会返回 {A: 1 B:default b C:3}

正如您所见, json.Unmarshal(例如,& ; out)将JSON解组为 out ,覆盖指定的值ied JSON,但保持其他领域不变。

As you can see, json.Unmarshal(example, &out) unmarshals the JSON into out, overwriting the values specified in the JSON, but leaving the other fields unchanged.

这篇关于如何在Go中解析JSON时指定默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆