gpt4 book ai didi

json - 将 JSON 解码为最小类型

转载 作者:数据小太阳 更新时间:2023-10-29 03:47:43 25 4
gpt4 key购买 nike

我有一个要解码的 Json 字符串。这是有效的:

jsonString := []byte(`{"my_int": 3, "my_string": null}`)
var data map[string]interface{}
err := json.Unmarshal(jsonString, &data)
if err != nil {
fmt.Println(err)
}
//avroJson := make(map[string]interface{})
for k, v := range data {
fmt.Printf("%v, %T\n", k, v)
}

我的问题是:my_int 的值 3 返回为 float64

我的问题是:如何解析具有“最小类型”的 json 字符串,以便 3 将返回 int32 而不是最大类型 3 => float64?

假设:我的 Json 很大并且只有原始类型,我想要一个真正为 float64 的最小值继续显示 float64

澄清:“最小类型”意味着如果 3 可以被视为 int32float64,则“最小类型”将是 int32,这是运行此代码时您将获得的确切类型:reflect.TypeOf(3).string()

最佳答案

由于您要解码到 interface{} 的映射中,golang json.Unmarshal documentation 的以下部分属于:

To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:
...
float64, for JSON numbers
string, for JSON strings
...

因此,要将样本数据解码为所需类型,您应该定义一个包含所需字段/类型映射的结构类型,例如:

type MyType struct {
MyInt int `json:"my_int"`
MyString *string `json:"my_string"`
}

foo := MyType{}
jsonstr := `{"my_int": 3, "my_string": null}`

err := json.Unmarshal([]byte(jsonstr), &foo)
if err != nil {
panic(err)
}
// foo => main.MyType{MyInt:3, MyString:(*string)(nil)}

关于json - 将 JSON 解码为最小类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48771909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com