Skip to content

majodev/nullable

 
 

Repository files navigation

Build Status GoDoc Go Report Card codecov

nullable

Provides ability to determine if a json key has been set to null or not provided. Inspired by How to determine if a JSON key has been set to null or not provided article by Jon Calhoun

Install

To get the package, execute:

go get github.com/allaboutapps/nullable

To import this package, add the following line to your code:

import "github.com/allaboutapps/nullable"

Refer to it as nullable.

For more details, see the API documentation.

Example

import "github.com/allaboutapps/nullable"

func main() {
	usr := struct {
		Name nullable.String `json:"name"`
	}{}

	data := []byte("{}")
	if err := json.Unmarshal(data, &usr); err != nil {
		log.Fatalf("unmarshaling failed: %s\n", err)
	}

	fmt.Println(usr.Name.Present) // false
	fmt.Println(usr.Name.Valid)   // false
	fmt.Println(usr.Name.Value)   // ""

	data = []byte("{\"name\":null}")
	if err := json.Unmarshal(data, &usr); err != nil {
		log.Fatalf("unmarshaling failed: %s\n", err)
	}

	fmt.Println(usr.Name.Present) // true
	fmt.Println(usr.Name.Valid)   // false
	fmt.Println(usr.Name.Value)   // ""

	data = []byte("{\"name\":\"John\"}")
	if err := json.Unmarshal(data, &usr); err != nil {
		log.Fatalf("unmarshaling failed: %s\n", err)
	}

	fmt.Println(usr.Name.Present) // true
	fmt.Println(usr.Name.Valid)   // true
	fmt.Println(usr.Name.Value)   // "John"
}

go-swagger usage example

definitions:
  NullableInt:
    type: integer
    example: 1234
    x-go-type:
      import:
        package: github.com/allaboutapps/nullable
      type: Int
  NullableInt16:
    type: integer
    example: 1234
    x-go-type:
      import:
        package: github.com/allaboutapps/nullable
      type: Int16
  NullableFloat:
    type: number
    format: float
    example: 1.5
    x-go-type:
      import:
        package: github.com/allaboutapps/nullable
      type: Float32
  NullableFloat64:
    type: number
    format: float
    example: 1.5
    x-go-type:
      import:
        package: github.com/allaboutapps/nullable
      type: Float64
  NullableString:
    type: string
    example: example
    x-go-type:
      import:
        package: github.com/allaboutapps/nullable
      type: String

Contributing

Please feel free to submit issues, fork the repository and send pull requests!

About

Provide types that allow to determine if a JSON key has been set to null or not provided. go-swagger compatible

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Go 70.9%
  • Dockerfile 18.1%
  • Makefile 8.3%
  • Shell 2.7%