In Go, you can compress and decompress JSON data using the compress/flate
or compress/gzip
packages. Here's how you can do it:
import (
"bytes"
"compress/flate"
"compress/gzip"
"encoding/json"
"io/ioutil"
)
compress/flate
package:func CompressJSON(data interface{}) ([]byte, error) {
// Convert data to JSON
jsonData, err := json.Marshal(data)
if err != nil {
return nil, err
}
// Create a buffer for compressed data
var buf bytes.Buffer
// Create a flate writer
fw, err := flate.NewWriter(&buf, flate.DefaultCompression)
if err != nil {
return nil, err
}
defer fw.Close()
// Write compressed data
_, err = fw.Write(jsonData)
if err != nil {
return nil, err
}
// Return compressed data
return buf.Bytes(), nil
}
compress/flate
package:func DecompressJSON(compressedData []byte) ([]byte, error) {
// Create a flate reader
fr := flate.NewReader(bytes.NewReader(compressedData))
defer fr.Close()
// Read decompressed data
decompressedData, err := ioutil.ReadAll(fr)
if err != nil {
return nil, err
}
// Return decompressed data
return decompressedData, nil
}
compress/gzip
package:func CompressJSONWithGzip(data interface{}) ([]byte, error) {
// Convert data to JSON
jsonData, err := json.Marshal(data)
if err != nil {
return nil, err
}
// Create a buffer for compressed data
var buf bytes.Buffer
// Create a gzip writer
gw := gzip.NewWriter(&buf)
defer gw.Close()
// Write compressed data
_, err = gw.Write(jsonData)
if err != nil {
return nil, err
}
// Return compressed data
return buf.Bytes(), nil
}
compress/gzip
package:func DecompressJSONWithGzip(compressedData []byte) ([]byte, error) {
// Create a gzip reader
gr, err := gzip.NewReader(bytes.NewReader(compressedData))
if err != nil {
return nil, err
}
defer gr.Close()
// Read decompressed data
decompressedData, err := ioutil.ReadAll(gr)
if err != nil {
return nil, err
}
// Return decompressed data
return decompressedData, nil
}
Now you can use these functions to compress and decompress JSON data in your Go code.