Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to stream object to gzipped json?

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?

like image 516
pdeva Avatar asked Mar 25 '19 23:03

pdeva


People also ask

What is JSON streaming and how does it work?

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.

How to compress and decompress gzip files in NodeJS?

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:

What is the best way to read JSON data?

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.

Are the elements of a JSON stream predictable?

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.


1 Answers

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]
like image 129
icza Avatar answered Nov 09 '22 07:11

icza