Possible issues with json deserialization in golang

  • 2020-06-15 09:13:58
  • OfStack

preface

In golang, when a floating-point number exceeds a definite value, golang displays it in scientific notation (as if anything greater than seven digits were a scientific notation).


var val float64
val = 1000000
fmt.Println(val) // ==> 1e+06

In daily development, we often encounter the problem of deserializing json passed from the front end, which we use because the data structure is unknown map[string]interface{} To receive the result of deserialization. Because golang parses json to interface{} When typing, follow these rules

bool stands for JSON booleans, float64 stands for JSON numbers, string stands for JSON strings, nil stands for JSON null.

So if there is a large number in json we receive, it will be parsed as float64 and possibly displayed as a scientific notation, as in this example


package main
import (
 "encoding/json"
 "fmt"
)

func main() {
 //Create the Json string
 var data = `
 {
 "id": 12423434, 
 "Name": "Fernando"
 }
 `

 //Marshal the json to a map
 var result map[string]interface{}
 err := json.Unmarshal([]byte(data), &result)
 if err != nil {
 fmt.Println(err.Error())
 return
 }
 fmt.Println(result)
}

Output the following results


map[id:1.2423434e+07 Name:Fernando]

If you pass it to the front end, the front end may report an error. So we'd better keep the original string representation of this number. using json.Number Type to represent

So just change to the following code


package main
import (
 "encoding/json"
 "fmt"
 "strings"
)

func main() {
 //Create the Json string
 var data = `
 {
 "id": 12423434, 
 "Name": "Fernando"
 }
 `
 //Marshal the json to a map
 var result map[string]interface{}
 d := json.NewDecoder(strings.NewReader(data))
 d.UseNumber()
 err := d.Decode(&result)
 if err != nil {
 fmt.Println(err.Error())
 return
 }
 //  At the moment result["id"] The type of json.Number the   Its underlying type is actually string
 fmt.Println(result)
}

Output the following results


map[id:12423434 Name:Fernando]

conclusion


Related articles: