go icon indicating copy to clipboard operation
go copied to clipboard

What is the difference between jsoniter.Number and stdjson.Number?

Open leiguowei opened this issue 4 years ago • 0 comments

We use jsoniter's Unmarshal and change the numeric field Unmarshal to json.Number, but found that the data format after Unmarshal is stdjson.Number instead of jsoniter.Number. I don’t know the purpose of this, whether it’s a bug or some remaining problems. And I want to know if we use stdjson.Number, if we upgrade the jsoniter package in the future, will it become jsoniter.Number, which will have an impact on our project. The code is pasted below.

package main

import (
	"bytes"
	"encoding/json"
	"fmt"

	jsoniter "github.com/json-iterator/go"
)

var j = jsoniter.ConfigDefault

func unmarshalWithJsonNumber(data []byte, v interface{}) error {
	d := j.NewDecoder(bytes.NewBuffer(data))
	d.UseNumber()
	return d.Decode(v)
}

func main() {
	data := map[string]interface{}{
		"name": "tom",
		"age":  20,
	}
	dataBytes, _ := j.Marshal(data)
	target := map[string]interface{}{}
	unmarshalWithJsonNumber(dataBytes, &target)
	age := target["age"]
	if value, ok := age.(json.Number); ok {
		fmt.Printf("std json number, %v\n", value)
	}
	if value, ok := age.(jsoniter.Number); ok {
		fmt.Printf("jsoniter number, %v\n", value)
	}
	// out: std json number, 20
}

leiguowei avatar Dec 29 '21 06:12 leiguowei