【问题标题】:golang unmarshall unknown json datagolang解组未知的json数据
【发布时间】:2021-07-22 12:55:35
【问题描述】:

我有一个用例需要解组来自 HTTP 请求的响应。我不提前知道响应格式,但只想将结果上游返回到 Web 客户端(类似于代理的功能) 通常我会像下面这样解组:

resp, _ = http.Post(url, "application/json", bytes.NewBuffer(jsonPayload))
body, _ := ioutil.ReadAll(resp.Body)
responseJson := make(map[string]interface{})
json.Unmarshal(body, &responseJson)

但是,如果结果是 JSON 数组 [{},{}...] 那么我需要执行以下操作

var responseList []map[string]interface{}
json.Unmarshal([]byte(body), &responseList)

如果结果是像"ok" 这样的单个字符串值,它还需要不同的解组方法

但如果我不提前知道响应类型,我怎么知道如何解组?

【问题讨论】:

  • json.RawMessage 代表任意 JSON 文档,但如果你只是想传递字节,为什么要解组呢?
  • 其实很好,我应该只返回 []byte/string

标签: json go unmarshalling


【解决方案1】:

您可以将其解组为如下界面:

var responseJson interface{}
json.Unmarshal(body, &responseJson)

读取响应类型:

switch resp := responseBody.(type) {
case string:
    fmt.Println(resp)
case float64:
    fmt.Println(int(resp))
default:
    fmt.Println(resp)
}

【讨论】:

  • 谢谢!这适用于数组和 json 类型,但是当它只是一个像 ok 这样的字符串时会中断
猜你喜欢
  • 1970-01-01
  • 2019-02-20
  • 2021-12-03
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 2017-09-07
  • 2017-09-23
  • 2021-11-04
相关资源
最近更新 更多