dongzhuo1930 2015-09-13 21:18
浏览 24
已采纳

Go的新手,试图弄清楚如何处理JSON

Coming from languages like Python, Ruby, and JS, I am really struggling with Go right now. It feels overly complex, but I am hoping I am just missing something.

Right now I have code that can successfully call Boston's MBTA API (using their public developer key) and return all route information.

I have dropped the code here: http://pastebin.com/PkBaP714 and here: http://pastebin.com/7mRxgrpp

Sample data returned: http://pastebin.com/M2hzMKYs

I want to return two things 1) JUST each route_type and mode_name, and 2) when route_type is called each of the route_id and route_name.

For whatever reason I am just totally lost. I've spent 16 hours staring at documentation and I feel like I am looking at a foreign language :).

It may be too much to ask for specific help, but I would LOVE IT.

  • 写回答

1条回答 默认 最新

  • dougaojue8185 2015-09-13 22:00
    关注

    Just map them to a new type:

    func main() {
        flag.Parse()
        c := gombta.Client{APIKey: apikey, URL: apiurl}
    
        // get a list of routes by type
        d, err := c.GetRoutes(format)
        check(err)
    
        var toPrint interface{}
    
        if typeid == 9999 {
            type Result struct {
                RouteType string `json:"route_type"`
                ModeName  string `json:"mode_name"`
            }
            rs := []Result{}
            for _, m := range d.Mode {
                rs = append(rs, Result{
                    RouteType: m.RouteType,
                    ModeName:  m.ModeName,
                })
            }
            toPrint = rs
        } else {
            type Result struct {
                RouteID   string `json:"route_id"`
                RouteName string `json:"route_name"`
            }
            rs := []Result{}
            for _, m := range d.Mode {
                if fmt.Sprint(typeid) == m.RouteType {
                    for _, r := range m.Route {
                        rs = append(rs, Result{
                            RouteID:   r.RouteID,
                            RouteName: r.RouteName,
                        })
                    }
                }
            }
            toPrint = rs
        }
    
        j, err := json.MarshalIndent(toPrint, "", " ")
        fmt.Printf("RouteTypes: ")
        os.Stdout.Write(j)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)