niljson

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2024 License: MIT Imports: 1 Imported by: 1

README

niljson - A simple Go package for (un-)marshalling null-able JSON types

GoDoc codecov Go Report Card REUSE status buy ma a coffee

niljson provides a simple and efficient way to handle nullable JSON fields during the (un-)marshalling process. In JSON, it's common to encounter fields that can be null, but handling these fields in Go can be cumbersome, especially when dealing with primitive types like int, float64, and bool. These types can all be either 0 (as a value) or null. In Go you can always work with pointers, but these can lead to unhandled nil pointer dereferences.

niljson addresses this challenge by offering a set of types that can seamlessly handle null values during unmarshalling, allowing your Go applications to work with JSON data more naturally and with fewer boilerplate checks for nil values.

Key Features
  • Nullable Types: Provides a range of nullable types (NilString, NilInt, NilFloat, NilBool, etc.) that are easy to use and integrate into your existing Go structs.
  • JSON Unmarshalling Support: Automatically handles the (un-)marshalling of JSON fields, converting null JSON values to Go's nil or zero values, depending on the context.
  • Minimalistic and Lightweight: Designed to be lightweight and unobtrusive, so it won't bloat your application or introduce unnecessary dependencies (only relies on the Go standard library)
Example Usage
package main

import (
    "encoding/json"
    "fmt"
    "os"
    
    "github.com/wneessen/niljson"
)

type JSONType struct {
    Bool       niljson.NilBoolean `json:"bool"`
    Float32    niljson.NilFloat32 `json:"float32,omitempty"`
    Float64    niljson.NilFloat64 `json:"float64"`
    Int        niljson.NilInt     `json:"int"`
    Int64      niljson.NilInt64   `json:"int64"`
    NullString niljson.NilString  `json:"nil"`
    String     niljson.NilString  `json:"string"`
}

func main() {
  data := []byte(`{
 		"bytes": "Ynl0ZXM=",
		"bool": true,
		"float32": null,
		"float64":0,
		"int": 123,
		"int64": 12345678901234,
		"nilvalue": null,
		"string":"test"
	}`)

  var example JSONType
  var output string
  if err := json.Unmarshal(data, &example); err != nil {
    fmt.Println("failed to unmarshal JSON:", err)
    os.Exit(1)
  }

  if example.Bool.NotNil() {
    output += fmt.Sprintf("Bool is: %t, ", example.Bool.Value())
  }
  if example.Float32.IsNil() {
    output += "Float 32 is nil, "
  }
  if example.Float64.NotNil() {
    output += fmt.Sprintf("Float 64 is: %f, ", example.Float64.Value())
  }
  if example.String.NotNil() {
    output += fmt.Sprintf("String is: %s", example.String.Value())
  }
  fmt.Println(output)
  
  data, err := json.Marshal(&example)
  if err != nil {
    fmt.Printf("failed to marshal JSON: %s", err)
    os.Exit(1)
  }
  fmt.Println(data)
}

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type NilBoolean

type NilBoolean = Variable[bool]

NilBoolean is an boolean type that can be nil

type NilByteSlice

type NilByteSlice = Variable[[]byte]

NilByteSlice is a []byte type that can be nil

type NilFloat32

type NilFloat32 = Variable[float32]

NilFloat32 is an float32 type that can be nil

type NilFloat64

type NilFloat64 = Variable[float64]

NilFloat64 is an float64 type that can be nil

type NilInt

type NilInt = Variable[int]

NilInt is an int type that can be nil

type NilInt64

type NilInt64 = Variable[int64]

NilInt64 is an int64 type that can be nil

type NilString

type NilString = Variable[string]

NilString is a string type that can be nil

type NilUInt added in v0.0.2

type NilUInt = Variable[uint]

NilUInt is an uint type that can be nil

type NilUInt16 added in v0.0.2

type NilUInt16 = Variable[uint16]

NilUInt16 is an uint16 type that can be nil

type NilUInt32 added in v0.0.2

type NilUInt32 = Variable[uint32]

NilUInt32 is an uint32 type that can be nil

type NilUInt64 added in v0.0.2

type NilUInt64 = Variable[uint64]

NilUInt64 is an uint64 type that can be nil

type NilUInt8 added in v0.0.2

type NilUInt8 = Variable[uint8]

NilUInt8 is an uint8 type that can be nil

type Variable

type Variable[T any] struct {
	// contains filtered or unexported fields
}

Variable is a generic variable type that can be null.

func NewVariable added in v0.0.4

func NewVariable[T any](value T) Variable[T]

NewVariable returns a new Variable of generic type

func (*Variable[T]) IsNil

func (v *Variable[T]) IsNil() bool

IsNil returns true when a Variable is nil

func (*Variable[T]) MarshalJSON added in v0.0.4

func (v *Variable[T]) MarshalJSON() ([]byte, error)

MarshalJSON satisfies the json.Marshaler interface for generic Variable types

Example
type JSONType struct {
	Bool       NilBoolean   `json:"bool"`
	ByteSlice  NilByteSlice `json:"bytes"`
	Float32    NilFloat32   `json:"float32,omitempty"`
	Float64    NilFloat64   `json:"float64"`
	Int        NilInt       `json:"int"`
	Int64      NilInt64     `json:"int64"`
	NullString NilString    `json:"nilvalue,omitempty"`
	String     NilString    `json:"string"`
	UInt       NilUInt      `json:"uint"`
	UInt8      NilUInt8     `json:"uint8"`
}

example := &JSONType{
	Bool:      NewVariable(false),
	ByteSlice: NewVariable([]byte("bytes")),
	Float64:   NewVariable(123.456),
	Int:       NewVariable(123),
	Int64:     NewVariable(int64(12345678901234)),
	String:    NewVariable("test"),
	UInt:      NewVariable(uint(123)),
}
data, err := json.Marshal(example)
if err != nil {
	fmt.Printf("failed to marshal JSON: %s", err)
	os.Exit(1)
}
fmt.Println(string(data))
Output:

{"bool":false,"bytes":"Ynl0ZXM=","float32":null,"float64":123.456,"int":123,"int64":12345678901234,"nilvalue":null,"string":"test","uint":123,"uint8":null}

func (*Variable[T]) NotNil

func (v *Variable[T]) NotNil() bool

NotNil returns true when a Variable is not nil

func (*Variable[T]) Omitted added in v0.1.0

func (v *Variable[T]) Omitted() bool

Omitted returns true if a value was omitted in the JSON

func (*Variable[T]) Reset

func (v *Variable[T]) Reset()

Reset resets the value to the Variable to a zero value and sets it to be nil

func (*Variable[T]) UnmarshalJSON

func (v *Variable[T]) UnmarshalJSON(data []byte) error

UnmarshalJSON satisfies the json.Unmarshaler interface for generic Variable types

Example
type JSONType struct {
	Bool       NilBoolean   `json:"bool"`
	ByteSlice  NilByteSlice `json:"bytes"`
	Float32    NilFloat32   `json:"float32,omitempty"`
	Float64    NilFloat64   `json:"float64"`
	Int        NilInt       `json:"int"`
	Int64      NilInt64     `json:"int64"`
	NullString NilString    `json:"nilvalue,omitempty"`
	String     NilString    `json:"string"`
}
data := []byte(`{
 		"bytes": "Ynl0ZXM=",
		"bool": true,
		"float32": null,
		"float64":0,
		"int": 123,
		"int64": 12345678901234,
		"nilvalue": null,
		"string":"test"
	}`)

var example JSONType
var output string
if err := json.Unmarshal(data, &example); err != nil {
	fmt.Println("failed to unmarshal JSON:", err)
	os.Exit(1)
}

if example.Bool.NotNil() {
	output += fmt.Sprintf("Bool is: %t, ", example.Bool.Value())
}
if example.Float32.IsNil() {
	output += "Float 32 is nil, "
}
if example.Float64.NotNil() {
	output += fmt.Sprintf("Float 64 is: %f, ", example.Float64.Value())
}
if example.String.NotNil() {
	output += fmt.Sprintf("String is: %s", example.String.Value())
}
fmt.Println(output)
Output:

Bool is: true, Float 32 is nil, Float 64 is: 0.000000, String is: test

func (*Variable[T]) Value

func (v *Variable[T]) Value() T

Value returns the value of the Variable

Jump to

Keyboard shortcuts

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