在Go中的任意JSON数据结构

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

Arbitrary JSON data structure in go

问题

我正在构建一个HTTP API,我的每个处理程序都返回JSON数据,所以我构建了一个包装函数来处理JSON编组和HTTP响应(我还包括了包装器的相关部分以及一个示例处理程序)。

传递任意嵌套的结构体的最佳方法是什么(这些结构体还包含任意类型/字段数量)。目前,我已经选择了一个具有字符串键和interface{}值的映射。这样做是有效的,但这是最符合Go语言惯例的方式吗?

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是一个任意嵌套结构体的切片
}
英文:

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

得分: 1

如果您事先不知道要获取的类型、结构和嵌套方式,那么只能将其解码为类似于map[string]interface{}的通用类型。所以这里没有什么“惯用的”或“非惯用的”之分。

(个人而言,我会尽量修复结构,避免“任意”的嵌套和组合。)

英文:

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.)

huangapple
  • 本文由 发表于 2013年7月25日 04:46:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/17844508.html
匿名

发表评论

匿名网友

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

确定