【问题标题】:How to retrieve nested map data "json.unmarshal()" as empty interface如何检索嵌套地图数据“json.unmarshal()”作为空接口
【发布时间】:2021-05-25 05:19:35
【问题描述】:

这似乎是一个简单的问题,但我还没有弄清楚如何去做:我有一个嵌套的地图项,打印出来时如下所示:

fmt.Println("s3Info:", s3Info)

打印输出:

s3Info: [[map[s3Config:map[bucket:testbucket-data s3Key:runs/6033fd684304200011ef3bc5/init/03a78d21-446a-41bc-b4c1-eb66e04f45e2/52c8a076-f6c4-4180-8625-38ca52482628] size:158971 type:s3 varType:File]]

我想知道如何从对象s3Info 中获取buckets3Key 的值?

我尝试使用s3Info.s3Config访问s3Config,但出现以下错误:

go/api_default_service_data_item.go:659:46: s3Info.s3Config undefined (type interface {} is interface with no methods)

我也尝试使用s3Info["s3Config"]访问s3Config,但随后报错:

go/api_default_service_data_item.go:660:46: invalid operation: s3Info["s3Config"] (type interface {} does not support indexing)

添加: 该代码是处理来自 API 端点的查询响应的程序的一部分,以下是代码:

var runData map[string]interface{}

json.Unmarshal(body, &runData)

p := runData["p"].(map[string]interface{})
init := p["init"].(map[string]interface{})
outputs := init["outputs"].(map[string]interface{})
for key, s3Info := range outputs {
    // printout s3Info
    fmt.Println("s3Info:", s3Info)
    // check type
    switch c := s3Info.(type) {
        case string:
            fmt.Println("Key:", key, "=>", "s3Info:", s3Info)
        default:
            fmt.Printf("s3Info Type: %T\n", c)
    }
    // type assert to map
    s3Info := outputs[key].(map[string]interface{})
    fmt.Println("Key:", key, "=>", "s3Config:", s3Info["s3Config"])
}

打印输出如下:

s3Info: [map[s3Config:map[bucket:testbucket-data s3Key:runs/6033fd684304200011ef3bc5/init/03a78d21-446a-41bc-b4c1-eb66e04f45e2/52c8a076-f6c4-4180-8625-38ca52482628] size:158971 type:s3 varType:File]]
s3Info Type: []interface {}
interface conversion: interface {} is []interface {}, not map[string]interface {}

【问题讨论】:

  • . 用于访问结构字段,您没有结构,您有地图。以下是巡回赛的相关部分:tour.golang.org/moretypes/19
  • 嗨@Adrian,我已经试过了,也失败了,请检查我新编辑的问题。
  • s3Info 是一个empty interface,因此需要使用type assertion(或reflection)。这些数据来自哪里? (空接口有其用途,但应该probably be avoided,除非确实需要使用)
  • s3Info 是我从另一个 API 服务获得的数据,是否需要将其声明为结构才能使用它?
  • 我会看看你是如何从其他服务中检索信息的;看起来它返回的是一个字符串,而不是您期望的 widgets.S3Info(另一个避免 interface{} 的原因!)。请参阅playground 以获取有关此错误如何发生的快速示例。

标签: json string dictionary go marshalling


【解决方案1】:

s3Infojson.Unmarshal() 解组为interface{} 数组,但不是映射。里面的内容可以通过type assertion[]interface{}检索到。

s3Config可以通过:

for _, s := range s3Info.([]interface{}) {
  s3Config := s.(map[string]interface{})["s3Config"]
}

感谢@brits 提供有用的link

【讨论】:

    猜你喜欢
    • 2019-12-23
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    • 2014-04-11
    • 2017-10-14
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    相关资源
    最近更新 更多