| 12345678910111213141516171819202122232425262728293031323334353637 |
- package jsonutil
- import (
- "bytes"
- "fmt"
- "math"
- "github.com/opencost/opencost/core/pkg/util/json"
- )
- // EncodeFloat64 encodes a float64 value to JSON, handling NaN and infinity values
- func EncodeFloat64(buffer *bytes.Buffer, name string, val float64, comma string) {
- var encoding string
- if math.IsNaN(val) || math.IsInf(val, 0) {
- encoding = fmt.Sprintf("\"%s\":null%s", name, comma)
- } else {
- encoding = fmt.Sprintf("\"%s\":%f%s", name, val, comma)
- }
- buffer.WriteString(encoding)
- }
- // EncodeString encodes a string value to JSON
- func EncodeString(buffer *bytes.Buffer, name, val, comma string) {
- buffer.WriteString(fmt.Sprintf("\"%s\":\"%s\"%s", name, val, comma))
- }
- // Encode encodes any object to JSON
- func Encode(buffer *bytes.Buffer, name string, obj interface{}, comma string) {
- buffer.WriteString(fmt.Sprintf("\"%s\":", name))
- if bytes, err := json.Marshal(obj); err != nil {
- buffer.WriteString("null")
- } else {
- buffer.Write(bytes)
- }
- buffer.WriteString(comma)
- }
|