json - 解码 JSON 值,可以是字符串或数字

标签 json go

当我对 REST API 进行 HTTP 调用时,我可能会以数字或字符串形式返回 JSON 值 count。在任何一种情况下,我都想将其编码为整数。我该如何在 Go 中处理这个问题?

最佳答案

使用“string”字段标签选项指定应将字符串转换为数字。 documentation选项是:

The "string" option signals that a field is stored as JSON inside a JSON-encoded string. It applies only to fields of string, floating point, integer, or boolean types. This extra level of encoding is sometimes used when communicating with JavaScript programs:

这是一个使用示例:

type S struct {
    Count int `json:"count,string"`
}

playground example

如果 JSON 值可以是数字或字符串,则解码为 interface{} 并在解码后转换为 int:

Count interface{} `json:"count,string"`

使用此函数将 interface{} 值转换为 int:

func getInt(v interface{}) (int, error) {
  switch v := v.(type) {
  case float64:
    return int(v), nil
  case string:
    c, err := strconv.Atoi(v)
    if err != nil {
       return 0, err
    }
    return c, nil
  default:
    return 0, fmt.Errorf("conversion to int from %T not supported", v)
  }
}

关于json - 解码 JSON 值,可以是字符串或数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47687271/

相关文章:

javascript - 带切片器的 Google 图表返回 : One or more participants failed to draw()×

ruby-on-rails - Rails:如何将多个对象渲染为JSON?

go - 如何解析 "2019-09-19 04:03:01.770080087 +0000 UTC"时间戳

javascript - 从数据对象创建嵌套的 UL 列表

c# - 如何使用 C# 将 DataTable 值转换为 json?

c# - 反序列化 SFDC REST 服务 JSON 响应

json - golang 类型转换。接口(interface)结构

go - 计时器 channel - 在循环内发出标准输出

tcp - 如何让 net.Read 等待 golang 中的输入?

go - 使 GO 构建适应不同的操作系统