jsonutil.go 993 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package jsonutil
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math"
  6. "github.com/opencost/opencost/core/pkg/util/json"
  7. )
  8. // EncodeFloat64 encodes a float64 value to JSON, handling NaN and infinity values
  9. func EncodeFloat64(buffer *bytes.Buffer, name string, val float64, comma string) {
  10. var encoding string
  11. if math.IsNaN(val) || math.IsInf(val, 0) {
  12. encoding = fmt.Sprintf("\"%s\":null%s", name, comma)
  13. } else {
  14. encoding = fmt.Sprintf("\"%s\":%f%s", name, val, comma)
  15. }
  16. buffer.WriteString(encoding)
  17. }
  18. // EncodeString encodes a string value to JSON
  19. func EncodeString(buffer *bytes.Buffer, name, val, comma string) {
  20. buffer.WriteString(fmt.Sprintf("\"%s\":\"%s\"%s", name, val, comma))
  21. }
  22. // Encode encodes any object to JSON
  23. func Encode(buffer *bytes.Buffer, name string, obj interface{}, comma string) {
  24. buffer.WriteString(fmt.Sprintf("\"%s\":", name))
  25. if bytes, err := json.Marshal(obj); err != nil {
  26. buffer.WriteString("null")
  27. } else {
  28. buffer.Write(bytes)
  29. }
  30. buffer.WriteString(comma)
  31. }