duanjiaonie6097 2013-07-24 20:46
浏览 49
已采纳

Go中的任意JSON数据结构

I'm building an http api and every one of my handlers returns JSON data, so I built a wrapper function that handles the JSON marshalling and http response (I've included the relevant section from the wrapper as well as one of the sample handlers below).

What is the best way to pass arbitrarily nested structs (the structs also contain arbitrary types/number of fields). Right now I've settled on a map with string keys and interface{} values. This works, but is this the most idiomatic go way to do this?

result := make(map[string]interface{})
customerList(httpRequest, &result)

j, err := json.Marshal(result)
if err != nil {
    log.Println(err)
    errs := `{"error": "json.Marshal failed"}`
    w.Write([]byte(errs))
    return
}
w.Write(j)


func customerList(req *http.Request, result *map[string]interface{}) {
    data, err := database.RecentFiftyCustomers()
    if err != nil {
        (*result)["error"] = stringifyErr(err, "customerList()")
        return
    }

    (*result)["customers"] = data//data is a slice of arbitrarily nested structs
}
  • 写回答

1条回答 默认 最新

  • dtv7174 2013-07-25 06:54
    关注

    If you do not know in advance what types, what structure and which nesting you get, there is no option but to decode it into something generic like map[string]interface{}. So nothing "idiomatic" or "non-idiomatic" here.

    (Personally I'd try to somehow fix the structs and not have "arbitrary" nestings, and combinations.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分