the-sett / json-optional / Json.Encode.Optional

Support for encoding optional fields in JSON.

If a record has Maybe fields in it, they could be encoded either as null or left out altogether.

A good HTTP API will usually treat null or missing in the same way. But there are unstable APIs out there that treat them differently. For example, a PUT request that treats null as meaning set something to null, but missing to mean leave something as it currently is.

This API lets you choose easily whether to use nulls or skip optional fields. It is also designed to keep the encoder looking clean with ( "fieldName", value ) tuples in a list.

Make fields.


type Field

Fields of JSON object that can be optional.

field : (a -> Json.Encode.Value) -> ( String, a ) -> Field

Creates a field that must always have a value.

optionalField : (a -> Json.Encode.Value) -> ( String, Maybe a ) -> Field

Creates a field that may have a value. When no value is set, this field will be encoded as null or skipped, depending on what behaviour is requested when building the object.

nullableField : (a -> Json.Encode.Value) -> ( String, Maybe a ) -> Field

Creates a field that may have a value. When no value is set, this field will always be encoded as null, ignoring any default behaviour requested when building the object.

skippableField : (a -> Json.Encode.Value) -> ( String, Maybe a ) -> Field

Creates a field that may have a value. When no value is set, this field will always be skipped, ignoring any default behaviour requested when building the object.

Make objects.

objectMaySkip : List Field -> Json.Encode.Value

Encodes a JSON object. Any optionalField that is Nothing is skipped in the output.

objectMayNullify : List Field -> Json.Encode.Value

Encodes a JSON object. Any optionalField that is Nothing is output as null.