How to compress and decompress JSON data in Go?

In Go, you can compress and decompress JSON data using the compress/flate or compress/gzip packages. Here's how you can do it:

  1. Import the required packages:
import ( "bytes" "compress/flate" "compress/gzip" "encoding/json" "io/ioutil" )
  1. Compress JSON Data using 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 }
  1. Decompress JSON data using 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 }
  1. Compress JSON Data using 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 }
  1. Decompress JSON data using 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.