dspx15491 2017-01-19 17:52
浏览 75
已采纳

golang json迭代不支持索引

I've got a problem with my json parsing in golang. I used some code to parse the json into a map[string]interface{}{} but when I try to iterate through a nested field, the error (type interface {} does not support indexing) is triggered.

I'd like to get the following informations :

  • iterate through each response->blogs and then get the url of original_size photo that lays in response->posts->blog_n->photos->original_size
  • meta->status
  • response->blog->total_posts and response->blog->name

Here's a link to a playground Thank you for your help !

  • 写回答

2条回答 默认 最新

  • dongpin1059 2017-01-19 18:34
    关注

    Is there a reason you want to use a map? To do the indexing you're talking about, with maps, I think you would need nested maps as well.

    Have you considered using nested structs, as described here, Go Unmarshal nested JSON structure and Unmarshaling nested JSON objects in Golang ?

    For your JSON data, here is a sample -- working but limited -- struct. Go will ignore the fields you don't use.

    func main() {
        //Creating the maps for JSON
        data := &Header{}
    
        //Parsing/Unmarshalling JSON encoding/json
        err := json.Unmarshal([]byte(input), &data)
    
        if err != nil {
            panic(err)
        }
    
        fmt.Printf("%+v
    ", m)
    }
    type Header struct {
        Response struct { 
            Blog struct {
                Title string `json:"title"`
            } `json:"blog"`
            Posts []struct {
                Id int64 `json:"id"`
            } `json:"posts"`
        } `json:"response"`
    }
    

    To get JSON with Go to do what you want, you have to brush up on JSON and it's relation to Go types.

    Notice posts: slices of structs are, in JSON, arrays of objects, [{..},{..}]

    In Go, only exported fields will be filled.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?