使用字段(由对象或字符串组成的数组)解组json [英] Go unmarshal json with a field that is an array of objects or strings

查看:40
本文介绍了使用字段(由对象或字符串组成的数组)解组json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在执行过程中,您将json解组到结构中.问题是我有一个api,可能会在请求之间更改键值的类型.

In go you unmarshal json into a struct. The problem is that I have an api that might change the type of the value of a key from request to request.

例如可能是内联对象的对象,例如:

For example objects that might be inlined objects like this:

{
  "mykey": [
    {obj1}, 
    {obj2}
  ]
}

但也可以通过键指向对象,如下所示:

but also point to objects by keys, like this:

{
  "mykey": [
    "/obj1/is/at/this/path", 
    "/obj2/is/at/this/other/path"
  ]
}

可以内联某些对象,但是可以从多个位置引用其他对象.

Some objects can be inlined, but others are referenced from multiple locations.

在javascript或python中这不是问题.只需检查类型即可.

In javascript or python this wouldn't be a problem. Just check the type.

解组和解析这两个对象的惯用方式是什么?反映是唯一的方法吗?

What's the go-idiomatic way to unmarshal and parse these two objects? Is Reflect the only way?

推荐答案

您可以将此JSON解组为如下结构:

You could unmarshal this JSON to a structure like the following:

type Data struct {
    MyKey []interface{} `json:"mykey"`
}

如果JSON包含字符串,则它们将被解码为数组中的字符串.如果JSON包含对象,则它们将被解码为 map [string] interface {} 值.您可以使用类型开关来区分两者.像这样:

If the JSON includes strings, they will be decoded as strings in the array. If the JSON includes objects, they will be decoded as map[string]interface{} values. You can distinguish between the two using a type switch. Something like this:

for i, v := range data.MyKey {
    switch x := v.(type) {
    case string:
        fmt.Println("Got a string: ", x)
    case map[string]interface{}:
        fmt.Printf("Got an object: %#v\n", x)
    }
}

您可以在此处使用此示例: http://play.golang.org/p/PzwFI2FSav

You can play around with this example here: http://play.golang.org/p/PzwFI2FSav

这篇关于使用字段(由对象或字符串组成的数组)解组json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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