doujiang5211 2017-11-20 20:19
浏览 781
已采纳

前往:将JSON字符串转换为map [string] interface {}

I'm trying to create a JSON representation within Go using a map[string]interface{} type. I'm dealing with JSON strings and I'm having a hard time figuring out how to avoid the JSON unmarshaler to automatically deal with numbers as float64s. As a result the following error occurs.

Ex. "{ 'a' : 9223372036854775807}" should be map[string]interface{} = [a 9223372036854775807 but in reality it is map[string]interface{} = [a 9.2233720368547758088E18]

I searched how structs can be used to avoid this by using json.Number but I'd really prefer using the map type designated above.

  • 写回答

1条回答 默认 最新

  • dongsi7759 2017-11-20 20:36
    关注

    The go json.Unmarshal(...) function automatically uses float64 for JSON numbers. If you want to unmarshal numbers into a different type then you'll have to use a custom type with a custom unmarshaler. There is no way to force the unmarshaler to deserialize custom values into a generic map.

    For example, here's how you could parse values of the "a" property as a big.Int.

    package main
    
    import (
      "encoding/json"
      "fmt"
      "math/big"
    )
    
    type MyDoc struct {
      A BigA `json:"a"`
    }
    
    type BigA struct{ *big.Int }
    
    func (a BigA) UnmarshalJSON(bs []byte) error {
      _, ok := a.SetString(string(bs), 10)
      if !ok {
        return fmt.Errorf("invalid integer %s", bs)
      }
      return nil
    }
    
    func main() {
      jsonstr := `{"a":9223372036854775807}`
      mydoc := MyDoc{A: BigA{new(big.Int)}}
    
      err := json.Unmarshal([]byte(jsonstr), &mydoc)
      if err != nil {
        panic(err)
      }
    
      fmt.Printf("OK: mydoc=%#v
    ", mydoc)
      // OK: mydoc=main.MyDoc{A:9223372036854775807}
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?