在 Go 中序列化混合类型的 JSON 数组 [英] Serialize a mixed type JSON array in Go
本文介绍了在 Go 中序列化混合类型的 JSON 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想返回一个看起来像这样的结构:
I want to return a structure that looks like this:
{
results: [
["ooid1", 2.0, "Söme text"],
["ooid2", 1.3, "Åther text"],
]
}
这是一个字符串数组,浮点数,unicode字符.
That's an array of arrags that is string, floating point number, unicode character.
如果是 Python,我可以:
If it was Python I'd be able to:
import json
json.dumps({'results': [["ooid1", 2.0, u"Söme text"], ...])
但是在 Go 中,您不能拥有混合类型的数组(或切片).
But in Go you can't have an array (or slice) of mixed types.
我想过使用这样的结构:
I thought of using a struct like this:
type Row struct {
Ooid string
Score float64
Text rune
}
但我不希望每个都成为字典,我希望它成为每个包含 3 个元素的数组.
But I don't want each to become a dictionary, I want it to become an array of 3 elements each.
推荐答案
使用[]interface{}
type Results struct {
Rows []interface{} `json:"results"`
}
如果您想访问存储在 []interface{}
for _, row := range results.Rows {
switch r := row.(type) {
case string:
fmt.Println("string", r)
case float64:
fmt.Println("float64", r)
case int64:
fmt.Println("int64", r)
default:
fmt.Println("not found")
}
}
这篇关于在 Go 中序列化混合类型的 JSON 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文