我有一个json文件:
{
"Path":"",
"Tables":[
{
"name":"testTable",
"content":{
"c1":[
1,
2,
3
]
}
}
]
}
当我把它解析成这些结构体时:
type Database struct {
Path string `json:"Path"`
Tables []Table `json:"Tables"`
}
type Table struct {
Name string `json:"name"`
Content map[Column][]any `json:"content"`
}
(我正在使用any
来将任何可能的值存储到数据库中)
然后遍历content和[]any,打印出数据类型,所有数据都是float64,正如我所期望的,除了最后一个值,它是一个int。c1
的输出是:
+1.000000e+000
+2.000000e+000
3
Playground示例
// You can edit this code!
// Click here and start typing.
package main
import (
"encoding/json"
)
type Column string
type Table struct {
Name string `json:"name"`
Content map[Column][]any `json:"content"`
}
type Database struct {
Path string `json:"Path"`
Tables []Table `json:"Tables"`
}
func (t *Table) Select(columns ...Column) Table {
var newTable Table
newTable.Content = make(map[Column][]any, 0)
for _, c := range columns {
if t.Content[c] != nil {
newTable.Content[c] = t.Content[c]
}
}
return newTable
}
func (d *Database) Get(table string) *Table {
for _, t := range d.Tables {
if t.Name == table {
return &t
}
}
return nil
}
func main() {
jsonStr := `{"Path":"","Tables":[{"name":"testTable","content":{"c1":[1,2,3,3],"c2":[2,2,1,1],"c3":[3,3,2,2]}}]}`
var db Database
if err := json.Unmarshal([]byte(jsonStr), &db); err != nil {
panic("error")
}
t := db.Get("testTable")
ts := t.Select("c1", "c2")
for _, v := range ts.Content {
for _, v2 := range v {
//println(v2.(int)) - panic
//println(v2.(float64)) - panic
switch v2.(type) {
case int:
println(v2.(int))
break
default:
println(v2.(float64))
}
}
}
}
1条答案
按热度按时间yrdbyhpb1#
试试
fmt.Printf("%f",v2)