github.com/cryptohub-digital/blockbook@v0.3.5-0.20240403155730-99ab40b9104c/common/jsonnumber.go (about)

     1  package common
     2  
     3  import (
     4  	"encoding/json"
     5  	"strconv"
     6  )
     7  
     8  // JSONNumber is used instead of json.Number after upgrade to go 1.14
     9  //
    10  //	to handle data which can be numbers in double quotes or possibly not numbers at all
    11  //
    12  // see https://github.com/golang/go/issues/37308
    13  type JSONNumber string
    14  
    15  // Float64 returns JSONNumber as float64
    16  func (c JSONNumber) Float64() (float64, error) {
    17  	f, err := strconv.ParseFloat(string(c), 64)
    18  	if err != nil {
    19  		return 0, err
    20  	}
    21  	return f, nil
    22  }
    23  
    24  // Int64 returns JSONNumber as int64
    25  func (c JSONNumber) Int64() (int64, error) {
    26  	i, err := strconv.ParseInt(string(c), 10, 64)
    27  	if err != nil {
    28  		return 0, err
    29  	}
    30  	return i, nil
    31  }
    32  
    33  func (c JSONNumber) String() string {
    34  	return string(c)
    35  }
    36  
    37  // MarshalJSON marsalls JSONNumber to []byte
    38  // if possible, return a number without quotes, otherwise string value in quotes
    39  // empty string is treated as number 0
    40  func (c JSONNumber) MarshalJSON() ([]byte, error) {
    41  	if len(c) == 0 {
    42  		return []byte("0"), nil
    43  	}
    44  	if f, err := c.Float64(); err == nil {
    45  		return json.Marshal(f)
    46  	}
    47  	return json.Marshal(string(c))
    48  }
    49  
    50  // UnmarshalJSON unmarshalls JSONNumber from []byte
    51  // if the value is in quotes, remove them
    52  func (c *JSONNumber) UnmarshalJSON(d []byte) error {
    53  	s := string(d)
    54  	l := len(s)
    55  	if l > 1 && s[0] == '"' && s[l-1] == '"' {
    56  		*c = JSONNumber(s[1 : l-1])
    57  	} else {
    58  		*c = JSONNumber(s)
    59  	}
    60  	return nil
    61  }