Currently the way to convert an object to json and gzip it is:
jsonBytes, _ := json.Marshal(payload)
//gzip json
var body bytes.Buffer
g := gzip.NewWriter(&body)
g.Write(jsonBytes)
g.Close()
This results in an intermediate large byte buffer jsonBytes
, whose only purpose is to be then converted into gzipped buffer.
Is there any way to stream the marshalling of the payload
object so it comes out gzipped in the first place?
It’s the native data format for web browsers and Node.js, with practically every other programming language providing libraries to serialize data to and from JSON. In this article, we’ll discuss the idea of JSON Streaming — that is, how do we process streams of JSON data that are extremely large, or potentially infinite in length.
We are using zlib npm module for achieving GZIP compression in NodeJS. Below are the methods for achieving GZIP compression and decompression in Node.js : 1. For GZIP Compression and upload GZIP file on AWS S3 bucket:
JsonReader and JsonWriter read/write the data as token, referred as JsonToken. It is the most powerful approach among the three approaches to process JSON. It has the lowest overhead and it is quite fast in read/write operations. It is analogous to Stax parser for XML.
However, most streaming techniques assume the elements of the JSON stream are predictable, and don’t depend on each other. For example, a JSON stream that reports data from weather stations may consist of a sequence of JSON objects, separated by newline characters.
Yes, you may use json.Encoder
to stream the JSON output, and similarly json.Decoder
to decode a streamed JSON input. They take any io.Writer
and io.Reader
to write the JSON result to / read from, including gzip.Writer
and gzip.Reader
.
For example:
var body bytes.Buffer
w := gzip.NewWriter(&body)
enc := json.NewEncoder(w)
payload := map[string]interface{}{
"one": 1, "two": 2,
}
if err := enc.Encode(payload); err != nil {
panic(err)
}
if err := w.Close(); err != nil {
panic(err)
}
To verify that it works, this is how we can decode it:
r, err := gzip.NewReader(&body)
if err != nil {
panic(err)
}
dec := json.NewDecoder(r)
payload = nil
if err := dec.Decode(&payload); err != nil {
panic(err)
}
fmt.Println("Decoded:", payload)
Which will output (try it on the Go Playground):
Decoded: map[one:1 two:2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With