douyi6818 2015-01-18 22:53
浏览 198
已采纳

在Go中序列化混合类型JSON数组

I want to return a structure that looks like this:

{
    results: [
        ["ooid1", 2.0, "Söme text"],
        ["ooid2", 1.3, "Åther text"],
    ]
}

That's an array of arrags that is string, floating point number, unicode character.

If it was Python I'd be able to:

import json
json.dumps({'results': [["ooid1", 2.0, u"Söme text"], ...])

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
}

But I don't want each to become a dictionary, I want it to become an array of 3 elements each.

  • 写回答

3条回答 默认 最新

  • ds0802 2015-01-18 23:14
    关注

    Use []interface{}

    type Results struct {
         Rows []interface{} `json:"results"`
    }
    

    You will then have to use type assertion if you want to access the values stored in []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")
        } 
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退