首页 > 解决方案 > 从 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)
}

标签: go

解决方案


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

推荐阅读