简体   繁体   English

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

[英]Go: Converting JSON string to map[string]interface{}

I'm trying to create a JSON representation within Go using a map[string]interface{} type.我正在尝试使用map[string]interface{}类型在 Go 中创建 JSON 表示。 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.我正在处理 JSON 字符串,我很难弄清楚如何避免 JSON 解组器自动将数字处理为 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] "{ 'a' : 9223372036854775807}"应该是map[string]interface{} = [a 9223372036854775807但实际上它是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.我通过使用json.Number搜索了如何使用结构来避免这种情况,但我真的更喜欢使用上面指定的map类型。

The go json.Unmarshal(...) function automatically uses float64 for JSON numbers. go json.Unmarshal(...)函数自动将 float64 用于 JSON 数字。 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 .例如,以下是如何将“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\n", mydoc)
  // OK: mydoc=main.MyDoc{A:9223372036854775807}
}
func jsonToMap(jsonStr string) map[string]interface{} {
    result := make(map[string]interface{})
    json.Unmarshal([]byte(jsonStr), &result)
    return result
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM