Go 的范围不能超过 <my var>(类型 interface {})

我正处于尝试围绕 Go 进行思考的婴儿阶段。目前,我正在模拟一个 API 请求,该请求返回一个包含对象数组的 JSON 格式的字符串。我试图找出最合适的方法来迭代每个记录并访问每个字段。最终,每个字段都将写入 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 {})

我有两个问题,我想:


嵌套循环是访问每条记录的每个属性的最有效/最高效的方法吗?

我需要做什么来解决这个错误?

更新


当我将解码的数据转储到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] 

]


慕森王
浏览 821回答 1
1回答

RISEBY

未声明类型时 json 包将解码为的默认值是:bool, for JSON booleansfloat64, for JSON numbersstring, for JSON strings[]interface{}, for JSON arraysmap[string]interface{}, for JSON objectsnil for JSON null由于每个record(在您的示例中)都是一个 json 对象,因此您可以map[string]interface{}像这样断言每个对象:for _, record := range view {&nbsp; &nbsp; log.Printf(" [===>] Record: %s", record)&nbsp; &nbsp; if rec, ok := record.(map[string]interface{}); ok {&nbsp; &nbsp; &nbsp; &nbsp; for key, val := range rec {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Printf(" [========>] %s = %s", key, val)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("record not a map[string]interface{}: %v\n", record)&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go