在Go中序列化混合类型的JSON数组 [英] Serialize a mixed type JSON array in Go

查看:125
本文介绍了在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屋!

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