jsonutil

package
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 26, 2026 License: MIT Imports: 4 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

jsonutil

Unified JSON encoding package that automatically formats JSON output based on environment mode.

Features

  • Automatic formatting: Compact JSON in production, pretty-printed in debug mode
  • Environment-based: Controlled via DIRIO_DEBUG environment variable
  • Drop-in replacement: Simple API compatible with standard encoding/json
  • Filesystem integration: Built-in support for billy.Filesystem

Usage

Basic Encoding
import "github.com/DirIO-S3/dirio/internal/jsonutil"

data := MyStruct{Name: "example", Count: 42}

// Automatically formats based on DIRIO_DEBUG
bytes, err := jsonutil.Marshal(data)
Encoding to File
import "github.com/DirIO-S3/dirio/internal/jsonutil"

data := MyStruct{Name: "example", Count: 42}

// Writes JSON to file, auto-formatted based on environment
err := jsonutil.MarshalToFile(fs, "config.json", data)
Decoding
import "github.com/DirIO-S3/dirio/internal/jsonutil"

var data MyStruct
err := jsonutil.Unmarshal(bytes, &data)

Formatting Control

The package automatically selects JSON formatting based on multiple sources (checked in order):

1. Environment Variable Override
DIRIO_DEBUG Output Format
1 or true Pretty-printed (indented with 2 spaces)
0, false, or unset Check config flags
2. Application Config Flags

The following flag combinations enable pretty-printed JSON:

Flags Pretty JSON
--debug Yes
--log-level=debug --verbosity=verbose Yes (both required)
Any other combination No (compact)
Examples

Production mode (default):

./dirio

Output: {"name":"example","count":42}

Debug mode - via flag:

./dirio --debug

Output:

{
  "name": "example",
  "count": 42
}

Debug mode - via log flags:

./dirio --log-level=debug --verbosity=verbose

Output:

{
  "name": "example",
  "count": 42
}

Debug mode - via environment:

export DIRIO_DEBUG=1
./dirio

Output:

{
  "name": "example",
  "count": 42
}

Migration Guide

Before
import "encoding/json"

// Inconsistent formatting across codebase
data1, err := json.MarshalIndent(user, "", "  ")  // User metadata
data2, err := json.Marshal(bucket)                 // Bucket metadata
data3, err := json.MarshalIndent(config, "", "  ") // Data config
After
import "github.com/DirIO-S3/dirio/internal/jsonutil"

// Consistent API, automatic formatting
data1, err := jsonutil.Marshal(user)    // Auto-formatted
data2, err := jsonutil.Marshal(bucket)  // Auto-formatted
data3, err := jsonutil.Marshal(config)  // Auto-formatted
File Writing - Before
import (
    "encoding/json"
    "github.com/DirIO-S3/dirio/internal/util"
)

data, err := json.Marshal(meta)
if err != nil {
    return err
}
return util.WriteFile(m.metadataFS, metaPath, data, 0644)
File Writing - After
import "github.com/DirIO-S3/dirio/internal/jsonutil"

return jsonutil.MarshalToFile(m.metadataFS, metaPath, meta)

Benefits

  1. Consistency: All JSON output follows the same formatting rules
  2. Simplicity: One function call handles both encoding and formatting
  3. Production-ready: Compact output reduces file sizes in production
  4. Developer-friendly: Pretty-printed output makes debugging easier
  5. No code changes: Switch between modes via environment variable only

Testing

Run the test suite:

go test ./internal/jsonutil/...

Test with debug mode:

DIRIO_DEBUG=1 go test ./internal/jsonutil/... -v

Documentation

Overview

Example (EnvironmentControl)

Example_environmentControl demonstrates how to control formatting

package main

import (
	"fmt"
	"os"

	"github.com/DirIO-S3/dirio/internal/jsonutil"
)

func main() {
	type Config struct {
		Debug bool `json:"debug"`
	}

	config := Config{Debug: true}

	// Save original env
	original := os.Getenv("DIRIO_DEBUG")
	defer func() {
		if original == "" {
			os.Unsetenv("DIRIO_DEBUG")
		} else {
			os.Setenv("DIRIO_DEBUG", original)
		}
	}()

	// Production mode (compact)
	os.Unsetenv("DIRIO_DEBUG")
	prodData, _ := jsonutil.Marshal(config)
	fmt.Printf("Production: %s\n", string(prodData))

	// Debug mode (pretty)
	os.Setenv("DIRIO_DEBUG", "1")
	debugData, _ := jsonutil.Marshal(config)
	fmt.Printf("Debug: %s\n", string(debugData))

}
Output:
Production: {"debug":true}
Debug: {
  "debug": true
}
Example (Migration)

Example_migration shows how to migrate from old code to new jsonutil package

package main

import (
	"fmt"

	"github.com/go-git/go-billy/v5/memfs"

	"github.com/DirIO-S3/dirio/internal/jsonutil"
)

func main() {
	// OLD CODE (inconsistent):
	// import "encoding/json"
	//
	// // Some files use MarshalIndent
	// userData, err := json.MarshalIndent(user, "", "  ")
	// if err != nil {
	//     return err
	// }
	// util.WriteFile(fs, "user.json", userData, 0o644)
	//
	// // Other files use Marshal
	// bucketData, err := json.Marshal(bucket)
	// if err != nil {
	//     return err
	// }
	// util.WriteFile(fs, "bucket.json", bucketData, 0o644)

	// NEW CODE (consistent, automatic):
	fs := memfs.New()

	type User struct {
		Name string `json:"name"`
	}
	type Bucket struct {
		Name string `json:"name"`
	}

	user := User{Name: "john"}
	bucket := Bucket{Name: "my-bucket"}

	// Both use the same function, formatting is automatic
	jsonutil.MarshalToFile(fs, "user.json", user)
	jsonutil.MarshalToFile(fs, "bucket.json", bucket)

	fmt.Println("Migration complete")
}
Output:
Migration complete

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Marshal

func Marshal(v any) ([]byte, error)

Marshal encodes v to JSON, automatically selecting compact or pretty format based on the current debug mode. Debug mode is enabled by:

  1. DIRIO_DEBUG environment variable (1 or true)
  2. --debug flag
  3. --log-level=debug AND --verbosity=verbose together

In debug mode, uses indented format with 2 spaces. In production mode (default), uses compact format.

Example

ExampleMarshal demonstrates automatic formatting based on environment

package main

import (
	"fmt"

	"github.com/DirIO-S3/dirio/internal/jsonutil"
)

func main() {
	type Config struct {
		Name    string `json:"name"`
		Version string `json:"version"`
	}

	config := Config{
		Name:    "dirio",
		Version: "1.0.0",
	}

	// Automatically formats based on DIRIO_DEBUG environment variable
	data, err := jsonutil.Marshal(config)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	fmt.Printf("Output: %s\n", string(data))
	// Output in production (DIRIO_DEBUG unset): {"name":"dirio","version":"1.0.0"}
	// Output in debug (DIRIO_DEBUG=1):
	// {
	//   "name": "dirio",
	//   "version": "1.0.0"
	// }
}

func MarshalToFile

func MarshalToFile(fs billy.Filesystem, path string, v any) error

MarshalToFile encodes v to JSON and writes it to the specified path on the given filesystem. Automatically selects compact or pretty format based on debug mode. Uses file permissions 0644 for the output file.

Example

ExampleMarshalToFile demonstrates writing JSON to a file

package main

import (
	"fmt"

	"github.com/go-git/go-billy/v5/memfs"

	"github.com/DirIO-S3/dirio/internal/jsonutil"
)

func main() {
	type UserMetadata struct {
		Username string `json:"username"`
		Email    string `json:"email"`
	}

	fs := memfs.New()
	user := UserMetadata{
		Username: "john",
		Email:    "john@example.com",
	}

	// Write to file with automatic formatting
	err := jsonutil.MarshalToFile(fs, "user.json", user)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}

	fmt.Println("User metadata saved successfully")
}
Output:
User metadata saved successfully

func Unmarshal

func Unmarshal(data []byte, v any) error

Unmarshal is a convenience wrapper around json.Unmarshal for consistency. It decodes JSON data into v.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL