A demonstration project showcasing the new encoding/json/v2 package in Go 1.25, comparing default JSON marshaling with custom marshalers for complex data types.
- Default JSON Encoding: Standard marshaling behavior for
time.Timeand*big.Float - Custom JSON Encoding: Custom marshalers for RFC3339 time formatting and big.Float as strings
- HTTP Server: Two endpoints demonstrating different encoding approaches
- Go 1.25 or later (required for
encoding/json/v2package)
git clone <repository-url>
cd go-jsonv2-playground
go mod tidy
go run cmd/main.goStart the server:
go run cmd/main.goThe server will start on http://localhost:8080 with two available endpoints.
Uses standard JSON marshaling without custom formatters.
Example Request:
curl http://localhost:8080/defaultExample Response:
{
"id": 1,
"timestamp": "2024-08-27T14:30:45.123456789Z",
"value": 12345.6789,
"message": "default encoding"
}Uses custom marshalers for enhanced formatting:
time.Timeformatted as RFC3339 strings*big.Floatvalues as quoted strings for precision- Zero struct fields omitted
Example Request:
curl http://localhost:8080/customExample Response:
{
"id": 2,
"timestamp": "2024-08-27T14:30:45Z",
"value": "98765.4321",
"message": "custom encoding"
}type Payload struct {
ID int `json:"id"`
Timestamp time.Time `json:"timestamp"`
Value *big.Float `json:"value"`
Message string `json:"message"`
}The project demonstrates two custom marshalers:
- Time RFC3339 Marshaler: Formats
time.Timeas RFC3339 strings - Big Float String Marshaler: Converts
*big.Floatto quoted string representation
var timeRFC3339 = json.MarshalFunc(func(t time.Time) ([]byte, error) {
return []byte(`"` + t.Format(time.RFC3339) + `"`), nil
})
var bigFloatAsString = json.MarshalFunc(func(f *big.Float) ([]byte, error) {
return []byte(`"` + f.Text('g', -1) + `"`), nil
})- Default endpoint: Uses
json.Marshal(p, json.StringifyNumbers(false)) - Custom endpoint: Uses multiple marshaling options:
json.Marshal(p, json.WithMarshalers(timeRFC3339), json.WithMarshalers(bigFloatAsString), json.OmitZeroStructFields(true), )
| Feature | Default | Custom |
|---|---|---|
| Time Format | Go's default time format | RFC3339 string |
| Big Float | Numeric representation | Quoted string |
| Zero Fields | Included | Omitted |
| Precision | May lose precision | Full precision preserved |
You can easily compare the outputs by running both endpoints:
# Default encoding
curl -s http://localhost:8080/default | jq '.'
# Custom encoding
curl -s http://localhost:8080/custom | jq '.'Create a simple test script:
#!/bin/bash
echo "=== Default Encoding ==="
curl -s http://localhost:8080/default | jq '.'
echo -e "\n=== Custom Encoding ==="
curl -s http://localhost:8080/custom | jq '.'This playground is useful for understanding:
- Migration from
encoding/jsontoencoding/json/v2 - Custom marshaling strategies for complex types
- Precision handling with
big.Floatin JSON - Time formatting options in JSON APIs
- Performance comparisons between encoding approaches