Skip to content

Instantly share code, notes, and snippets.

@byBretema
Last active October 3, 2018 14:45
Show Gist options
  • Save byBretema/bb6f170df981f508e342a2588469eea7 to your computer and use it in GitHub Desktop.
Save byBretema/bb6f170df981f508e342a2588469eea7 to your computer and use it in GitHub Desktop.
Golang funcs that wraps json operations with "generics" and fix .0 floats values in marshal process
package jst
// Made with <3 by @cambalamas
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"math"
"os"
)
// JSONFileToBytes return json as bytes and error if produced while reading
func JSONFileToBytes(filePath string) []byte {
jsonFile, err := os.Open(filePath)
if err != nil {
log.Println(errors.New("ERR_OpeningFile"))
// TODO : CONTROL ERROR WITH CONTEXT
return nil
}
defer jsonFile.Close()
jsonBytes, err := ioutil.ReadAll(jsonFile)
if err != nil {
log.Println(errors.New("ERR_ReadingFromFile"))
// TODO : CONTROL ERROR WITH CONTEXT
return nil
}
return jsonBytes
}
// JSONtoOBJ deserialize a json file into go struct
func JSONtoOBJ(jsonFilePath string, obj interface{}) {
jsonBytes := JSONFileToBytes(jsonFilePath)
err := json.Unmarshal(jsonBytes, &obj)
if err != nil {
log.Println(err)
log.Println(errors.New("ERR_UnmarshalingJSON"))
// TODO : CONTROL ERROR WITH CONTEXT
}
}
// OBJtoJSON serialize a go struct into a json bytes
func OBJtoJSON(obj interface{}) []byte {
jsonBytes, err := json.Marshal(obj)
if err != nil {
log.Println(err)
log.Println(errors.New("ERR_MarshalingJSON"))
// TODO : CONTROL ERROR WITH CONTEXT
return nil
}
return jsonBytes
}
// JSONmap parse json file into a map
func JSONmap(filePath string) map[string]interface{} {
var data map[string]interface{}
jsonBytes := JSONFileToBytes(filePath)
json.Unmarshal(jsonBytes, &data)
return data
}
// Own type for float64 to allow .0 floats
type jFloat64 float64
// MarshalJSON interface implementation for our own float type
// allowing .0 floats
func (jF jFloat64) MarshalJSON() ([]byte, error) {
const eps = 1e-12
v := float64(jF)
w, f := math.Modf(v)
if f < eps {
return []byte(fmt.Sprintf(`%v.0`, math.Trunc(w))), nil
}
return json.Marshal(v)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment