JsonCompressor is a lightweight Go library that compresses JSON structures into arrays by preserving only the values while maintaining the field order. It's particularly useful when you need to reduce JSON payload size while retaining the ability to reconstruct the original structure.
- Compress any struct with JSON tags into an array format
- Decompress arrays back into their original struct format
- Recursive handling of nested structures, pointers, slices/arrays and string-keyed maps
- Preserves field order based on struct definition
- Type-safe conversion
go get github.com/go-sphere/jsoncompressortype Person struct {
Name string `json:"name"`
Age int `json:"age"`
Hobbies []string `json:"hobbies"`
Address struct {
City string `json:"city"`
Country string `json:"country"`
} `json:"address"`
}
// Create a sample struct
person := Person{
Name: "John Doe",
Age: 30,
Hobbies: []string{"reading", "coding"},
Address: struct {
City string `json:"city"`
Country string `json:"country"`
}{
City: "New York",
Country: "USA",
},
}
// Compress
compressed, err := jsoncompressor.Marshal(person)
if err != nil {
log.Fatal(err)
}
// Result: ["John Doe", 30, ["reading", "coding"], ["New York", "USA"]]
// Decompress
var decompressed Person
err = jsoncompressor.Unmarshal(compressed, &decompressed)
if err != nil {
log.Fatal(err)
}| Go type | Compressed form |
|---|---|
| struct | Array of its field values |
| pointer | The pointed-to value's form, or null when nil |
| slice / array | Array |
| map with string keys | Object |
types implementing json.Marshaler and json.Unmarshaler |
Their MarshalJSON output |
scalars / interface{} |
Value as-is |
Channels, functions, unsafe.Pointer, uintptr and maps with non-string keys are
unsupported: Marshal returns an error when it meets one.
- Only exported fields with a non-empty
jsontag take part; untagged fields and fields taggedjson:"-"are skipped - Field order must be consistent between compression and decompression
- Requires proper type matching for successful decompression
- Types implementing both
json.Marshalerandjson.Unmarshaler(such astime.Time) keep their own JSON form instead of being expanded into an array; embedding one in a struct promotes those methods, as withencoding/json - Integers decode exactly across the full
int64/uint64range; numbers stored intointerface{}fields decode asfloat64, as withencoding/json
MIT License
Contributions are welcome! Please feel free to submit a Pull Request.