[英]How to retrieve nested map data “json.unmarshal()” as empty interface
這似乎是一個簡單的問題,但我還沒有弄清楚如何去做:我有一個嵌套的 map 項目,打印出來時如下所示:
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]]
我想知道如何從 object s3Info
獲取bucket
和s3Key
的值?
我嘗試使用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 {}
s3Info
由json.Unmarshal()
解組為interface{}
數組,但不是 map。 可以通過對[]interface{}
的type assertion
來檢索里面的內容。
s3Config
可以通過以下方式獲取:
for _, s := range s3Info.([]interface{}) {
s3Config := s.(map[string]interface{})["s3Config"]
}
感謝@brits 提供有用的鏈接:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.