Go 无法对 ``(类型为 interface{})进行 range 迭代。

huangapple go评论65阅读模式
英文:

Go cannot range over <my var> (type interface {})

问题

我正在尝试理解Go语言的基础知识。目前,我正在模拟一个返回包含对象数组的JSON格式字符串的API请求。我正在努力找出最合适的方法来迭代每个记录并访问每个字段。最终,每个字段将被写入Excel电子表格,但现在我只想打印每个字段的键和值。

以下是我的代码(我会在Go Playground中提供它,但不支持HTTP请求):

response, err := http.Get("http://go-proto.robwilkerson.org/demo.json")
failOnError(err, "Uh oh")
defer response.Body.Close()

var view []interface{}
json.NewDecoder(response.Body).Decode(&view)
log.Printf(" [x] Pulled JSON: %s", view)
for _, record := range view {
	log.Printf(" [==>] Record: %s", record)

	for key, val := range record {
		log.Printf(" [========>] %s = %s", key, val)
	}
}

一切都正常工作,直到尝试迭代包含每个记录属性的map的嵌套循环时出现以下错误:

cannot range over record (type interface {})

我有两个问题:

  1. 嵌套循环是访问每个记录的每个属性的最有效/高效的方法吗?
  2. 我需要做什么来解决这个错误?

更新

当我将解码为view变量的数据转储时,得到以下日志结果:

[
    map[id:ef14912f-8031-42b3-8c50-7aa612287534 avatar:http://placehold.it/32x32 name:Vilma Hobbs email:vilmahobbs@exiand.com phone:+1 (886) 549-3522 address:471 Dahill Road, Jacksonwald, Alabama, 6026] 
    map[id:1b7bf182-2482-4b8b-8210-9dc9ee51069e avatar:http://placehold.it/32x32 name:Anne Dalton email:annedalton@exiand.com phone:+1 (994) 583-2947 address:660 Macdougal Street, Ticonderoga, Alaska, 7942] 
    map[id:f8027852-f52e-4bbb-bc9d-fb5e34929b40 avatar:http://placehold.it/32x32 name:Amie Ray email:amieray@exiand.com phone:+1 (853) 508-3649 address:878 Kane Street, Derwood, Minnesota, 3826] 
    map[id:b9842ab7-5053-48b4-a991-f5c63af8fb7e avatar:http://placehold.it/32x32 name:Hope Benton email:hopebenton@exiand.com phone:+1 (938) 542-2232 address:396 Osborn Street, Rowe, Massachusetts, 702] 
    map[id:8f9f6d8d-d14e-4ddc-acb2-eb96d3c3d7a8 avatar:http://placehold.it/32x32 name:Janine Kidd email:janinekidd@exiand.com phone:+1 (877) 474-2633 address:173 Manhattan Court, Hall, Virginia, 7376] 
    map[avatar:http://placehold.it/32x32 name:Kristen Yang email:kristenyang@exiand.com phone:+1 (862) 469-3446 address:203 Doughty Street, Westmoreland, Rhode Island, 849 id:210a6ae6-8227-4f26-a47c-448c400f26e9] 
    map[name:Murray Sosa email:murraysosa@exiand.com phone:+1 (814) 549-2536 address:811 Kingsland Avenue, Shepardsville, Hawaii, 9117 id:05f4f6af-19af-4b76-9aa8-9352281cf7d9 avatar:http://placehold.it/32x32] 
    map[phone:+1 (918) 476-2264 address:176 Underhill Avenue, Ebro, Washington, 8099 id:9d21268d-067c-4b16-a6cd-42d184c4c059 avatar:http://placehold.it/32x32 name:Paige Stanton email:paigestanton@exiand.com] 
    map[id:9946c19f-c226-4ff3-b578-57a249f8d0c7 avatar:http://placehold.it/32x32 name:Melisa Oconnor email:melisaoconnor@exiand.com phone:+1 (908) 429-3915 address:768 Wallabout Street, Cotopaxi, Florida, 3388] 
    map[id:ee0b82cb-4990-428b-ba36-088287a404ba avatar:http://placehold.it/32x32 name:Monique Poole email:moniquepoole@exiand.com phone:+1 (925) 564-2690 address:232 Hubbard Place, Islandia, Michigan, 3722]
]
英文:

I'm in the infant stages of trying to wrap my mind around Go. At the moment, I'm simulating an API request that returns a JSON-formatted string containing an array of objects. I'm trying to figure out the most appropriate way to iterate over each record and access each field. Ultimately, each field will be written to an Excel spreadsheet, but for now I just want to print each field's key & value.

Here's what I have (I'd provide it in the Go Playground, but HTTP requests aren't supported):

	response, err := http.Get(&quot;http://go-proto.robwilkerson.org/demo.json&quot;)
	failOnError(err, &quot;Uh oh&quot;)
	defer response.Body.Close()

	var view []interface{}
	json.NewDecoder(response.Body).Decode(&amp;view)
	log.Printf(&quot; [x] Pulled JSON: %s&quot;, view)
	for _, record := range view {
		log.Printf(&quot; [===&gt;] Record: %s&quot;, record)

		for key, val := range record {
			log.Printf(&quot; [========&gt;] %s = %s&quot;, key, val)
		}
	}

Everything works fine until the nested loop that attempts to iterate over the map that holds the properties of each record:

cannot range over record (type interface {})

I have two questions, I guess:

  1. Is the nested loop the most effective/efficient means of accessing each property of each record?
  2. What do I need to do to work around that error?

UPDATE

When I dump the data that is decoded into the view variable, this is the logged result:

[
    map[id:ef14912f-8031-42b3-8c50-7aa612287534 avatar:http://placehold.it/32x32 name:Vilma Hobbs email:vilmahobbs@exiand.com phone:+1 (886) 549-3522 address:471 Dahill Road, Jacksonwald, Alabama, 6026] 
    map[id:1b7bf182-2482-4b8b-8210-9dc9ee51069e avatar:http://placehold.it/32x32 name:Anne Dalton email:annedalton@exiand.com phone:+1 (994) 583-2947 address:660 Macdougal Street, Ticonderoga, Alaska, 7942] 
    map[id:f8027852-f52e-4bbb-bc9d-fb5e34929b40 avatar:http://placehold.it/32x32 name:Amie Ray email:amieray@exiand.com phone:+1 (853) 508-3649 address:878 Kane Street, Derwood, Minnesota, 3826] 
    map[id:b9842ab7-5053-48b4-a991-f5c63af8fb7e avatar:http://placehold.it/32x32 name:Hope Benton email:hopebenton@exiand.com phone:+1 (938) 542-2232 address:396 Osborn Street, Rowe, Massachusetts, 702] 
    map[id:8f9f6d8d-d14e-4ddc-acb2-eb96d3c3d7a8 avatar:http://placehold.it/32x32 name:Janine Kidd email:janinekidd@exiand.com phone:+1 (877) 474-2633 address:173 Manhattan Court, Hall, Virginia, 7376] 
    map[avatar:http://placehold.it/32x32 name:Kristen Yang email:kristenyang@exiand.com phone:+1 (862) 469-3446 address:203 Doughty Street, Westmoreland, Rhode Island, 849 id:210a6ae6-8227-4f26-a47c-448c400f26e9] 
    map[name:Murray Sosa email:murraysosa@exiand.com phone:+1 (814) 549-2536 address:811 Kingsland Avenue, Shepardsville, Hawaii, 9117 id:05f4f6af-19af-4b76-9aa8-9352281cf7d9 avatar:http://placehold.it/32x32] 
    map[phone:+1 (918) 476-2264 address:176 Underhill Avenue, Ebro, Washington, 8099 id:9d21268d-067c-4b16-a6cd-42d184c4c059 avatar:http://placehold.it/32x32 name:Paige Stanton email:paigestanton@exiand.com] 
    map[id:9946c19f-c226-4ff3-b578-57a249f8d0c7 avatar:http://placehold.it/32x32 name:Melisa Oconnor email:melisaoconnor@exiand.com phone:+1 (908) 429-3915 address:768 Wallabout Street, Cotopaxi, Florida, 3388] 
    map[id:ee0b82cb-4990-428b-ba36-088287a404ba avatar:http://placehold.it/32x32 name:Monique Poole email:moniquepoole@exiand.com phone:+1 (925) 564-2690 address:232 Hubbard Place, Islandia, Michigan, 3722]
]

答案1

得分: 52

json包在类型未声明时解码的默认值为:

  • bool,用于JSON布尔值
  • float64,用于JSON数字
  • string,用于JSON字符串
  • []interface{},用于JSON数组
  • map[string]interface{},用于JSON对象
  • nil,用于JSON null

由于每个record(在你的示例中)都是一个JSON对象,你可以将每个record断言为map[string]interface{},如下所示:

for _, record := range view {
    log.Printf(" [===>] Record: %s", record)

    if rec, ok := record.(map[string]interface{}); ok {
        for key, val := range rec {
            log.Printf(" [========>] %s = %s", key, val)
        }
    } else {
        fmt.Printf("record not a map[string]interface{}: %v\n", record)
    }
}
英文:

The defaults that the json package will decode into when the type isn't declared are:

bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null

Since each record is (in your example) a json object, you can assert each one as a map[string]interface{} like so:

for _, record := range view {
	log.Printf(&quot; [===&gt;] Record: %s&quot;, record)

	if rec, ok := record.(map[string]interface{}); ok {
		for key, val := range rec {
			log.Printf(&quot; [========&gt;] %s = %s&quot;, key, val)
		}
	} else {
		fmt.Printf(&quot;record not a map[string]interface{}: %v\n&quot;, record)
	}
}

huangapple
  • 本文由 发表于 2015年8月5日 01:50:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/31815969.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定