json.go 887 B

123456789101112131415161718192021222324252627282930313233343536
  1. package kubecost
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math"
  6. "github.com/opencost/opencost/pkg/util/json"
  7. )
  8. // TODO move everything below to a separate package
  9. func jsonEncodeFloat64(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. func jsonEncodeString(buffer *bytes.Buffer, name, val, comma string) {
  19. buffer.WriteString(fmt.Sprintf("\"%s\":\"%s\"%s", name, val, comma))
  20. }
  21. func jsonEncode(buffer *bytes.Buffer, name string, obj interface{}, comma string) {
  22. buffer.WriteString(fmt.Sprintf("\"%s\":", name))
  23. if bytes, err := json.Marshal(obj); err != nil {
  24. buffer.WriteString("null")
  25. } else {
  26. buffer.Write(bytes)
  27. }
  28. buffer.WriteString(comma)
  29. }