go - 从 API 调用响应创建嵌套 JSON
问题描述
如何根据从 API 收到的响应创建嵌套的 JSON 响应?
例如,我从一个 API 中得到一个resp
( *http.Response
),我希望它是一个对象列表 ( [{},{},{},...]
)
我想像这样创建一个响应
{
total: 1234,
addresses: [{},{},{}]
}
我不太确定如何处理这个问题。我接近了,因为下面的代码返回了类似的结构,但我的addresses
部分返回了一个转义字符串,如下所示
"[{\"access\":\"INTERNAL\",\"address\":\"1P9SnpTait5bS\"}]"
func (h *Handler) getAddresses(w http.ResponseWriter, r *http.Request) {
type Message struct {
Total int `json:total`
Addresses string `json:addresses`
}
resp, _ := h.Search(address, page, pageOffset) // *http.Response
body, _ := ioutil.ReadAll(resp.Body)
res := Message{
Total: total,
Addresses: string(body),
}
m, _ := json.Marshal(res)
w.Write(m)
}
解决方案
json.RawMessage
如果您只需要传递 json,则可以使用。
func (h *Handler) getAddresses(w http.ResponseWriter, r *http.Request) {
type Message struct {
Total int `json:"total"`
Addresses json.RawMessage `json:"addresses"`
}
resp, err := h.Search(address, page, pageOffset) // *http.Response
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
res := Message{
Total: total,
Addresses: json.RawMessage(body),
}
if err := json.NewEncoder(w).Encode(res); err != nil {
log.Println("failed to respond with json:", err)
}
}
推荐阅读
- c# - HTTP 触发 Azure 函数上传文件
- sql-server - SSRS - 与分组斗争
- node.js - sveltejs:如何在 sveltejs 样板 rollup.config.js 中更改 ip 和主机?
- python - 你如何使用通过 GitHub 安装的新包?
- dask - 限制客户端进行 client.restart() 调用是多用户集群
- c# - C# - 设置新创建的 xml 文件的构建操作的代码
- python - 无法为 Python 导入 Sklearn 库
- python - 当目标标签只有 0 和 1 时,如何对深度神经网络进行监督训练?
- c# - C# 无法通过换行符分割字符串\n
- python - 在熊猫数据框的标题行之前添加具有 excel countif 条件的行