Json.Decode

JSON

Decode Json.Value / JSON text into Selm values.

Combinators for shared API codecs include oneOf, nullable, at, map3...map8, dict, array, oneOrMore, and structured Error / errorToString.

For record-shaped JSON, prefer Json.Decode.Pipeline (succeed Ctor |> required "field" decoder) over large mapN chains.

For untyped walks (webhooks, jsonb), see Json.Decode.Dynamic.

Types

Decoder

type Decoder a = Decoder

A decoder that turns JSON into a value of type a.

Examples

string : Decoder String
int : Decoder Int

decodeString string "\"hi\"" == Ok "hi"
decodeString int "42" == Ok 42

Error

type Error
= Field String Error
| Index Int Error
| OneOf (List Error)
| Failure String Value

A structured error describing exactly how the decoder failed.

Examples

case decodeString int "true" of
    Ok n ->
        String.fromInt n

    Err err ->
        errorToString err

Values

decodeString

decodeString : Decoder a -> String -> Result Error a

Parse a JSON string with a decoder.

Examples

decodeString int "4" == Ok 4
decodeString int "1 + 2" == Err ...

decodeValue

decodeValue : Decoder a -> Value -> Result Error a

Decode a stored Json.Value (same representation as JSON text).

Examples

decodeValue int (Json.Encode.int 42) == Ok 42
decodeValue string (Json.Encode.string "hi") == Ok "hi"

errorToString

errorToString : Error -> String

Convert a decoding error into a String for debugging.

Examples

case decodeString int "true" of
    Ok _ ->
        "ok"

    Err err ->
        errorToString err

string

string : Decoder String

Decode a JSON string into a Selm String.

Examples

decodeString string "true" == Err ...
decodeString string "42" == Err ...
decodeString string "3.14" == Err ...
decodeString string "\"hello\"" == Ok "hello"
decodeString string "{ \"hello\": 42 }" == Err ...

int

int : Decoder Int

Decode a JSON number into a Selm Int.

Examples

decodeString int "true" == Err ...
decodeString int "42" == Ok 42
decodeString int "3.14" == Err ...
decodeString int "\"hello\"" == Err ...
decodeString int "{ \"hello\": 42 }" == Err ...

bool

bool : Decoder Bool

Decode a JSON boolean into a Selm Bool.

Examples

decodeString bool "true" == Ok True
decodeString bool "42" == Err ...
decodeString bool "3.14" == Err ...
decodeString bool "\"hello\"" == Err ...
decodeString bool "{ \"hello\": 42 }" == Err ...

float

float : Decoder Float

Decode a JSON number into a Selm Float.

Examples

decodeString float "true" == Err ...
decodeString float "42" == Ok 42
decodeString float "3.14" == Ok 3.14
decodeString float "\"hello\"" == Err ...
decodeString float "{ \"hello\": 42 }" == Err ...

nullable

nullable : Decoder a -> Decoder (Maybe a)

Decode a nullable JSON value into a Selm value.

Examples

decodeString (nullable int) "13" == Ok (Just 13)
decodeString (nullable int) "42" == Ok (Just 42)
decodeString (nullable int) "null" == Ok Nothing
decodeString (nullable int) "true" == Err ...

list

list : Decoder a -> Decoder (List a)

Decode a JSON array into a Selm List.

Examples

decodeString (list int) "[1,2,3]" == Ok [1,2,3]
decodeString (list bool) "[true,false]" == Ok [True,False]

array

array : Decoder a -> Decoder (Array a)

Decode a JSON array into an Array.

Examples

decodeString (array int) "[1,2,3]" == Ok (Array.fromList [1,2,3])
decodeString (array bool) "[true,false]" == Ok (Array.fromList [True,False])

dict

dict : Decoder a -> Decoder (Dict String a)

Decode a JSON object into a Dict.

Examples

decodeString (dict int) "{ \"alice\": 42, \"bob\": 99 }"
    == Ok (Dict.fromList [("alice", 42), ("bob", 99)])

If you need the keys available in the Dict values as well, use a private intermediate type and Dict.map after dict.

keyValuePairs

keyValuePairs : Decoder a -> Decoder (List (String, a))

Decode a JSON object into a list of key/value pairs.

Examples

decodeString (keyValuePairs int) "{ \"alice\": 42, \"bob\": 99 }"
    == Ok [("alice", 42), ("bob", 99)]

oneOrMore

oneOrMore : (a -> List a -> value) -> Decoder a -> Decoder value

Decode a JSON array that has one or more elements.

Examples

decodeString (oneOrMore (::) int) "[1,2,3]" == Ok [1,2,3]
decodeString (oneOrMore (::) int) "[]" == Err ...

field

field : String -> Decoder a -> Decoder a

Decode a JSON object, requiring a particular field.

Examples

decodeString (field "x" int) "{ \"x\": 3 }" == Ok 3
decodeString (field "x" int) "{ \"x\": 3, \"y\": 4 }" == Ok 3
decodeString (field "x" int) "{ \"x\": true }" == Err ...
decodeString (field "x" int) "{ \"y\": 4 }" == Err ...

decodeString (field "name" string) "{ \"name\": \"tom\" }" == Ok "tom"

The object *can* have other fields. The only thing this decoder cares about is if x is present and that the value there is an Int.

Check out map2 to see how to decode multiple fields!

at

at : List String -> Decoder a -> Decoder a

Decode a nested JSON object, requiring certain fields.

Examples

json = """{ "person": { "name": "tom", "age": 42 } }"""

decodeString (at ["person", "name"] string) json == Ok "tom"
decodeString (at ["person", "age"] int) json == Ok 42

This is really just a shorthand for saying things like:

field "person" (field "name" string) == at ["person","name"] string

index

index : Int -> Decoder a -> Decoder a

Decode a JSON array, requiring a particular index.

Examples

json = """[ "alice", "bob", "chuck" ]"""

decodeString (index 0 string) json == Ok "alice"
decodeString (index 1 string) json == Ok "bob"
decodeString (index 2 string) json == Ok "chuck"
decodeString (index 3 string) json == Err ...

maybe

maybe : Decoder a -> Decoder (Maybe a)

Helpful for dealing with optional fields. Here are a few slightly different examples:

Examples

json = """{ "name": "tom", "age": 42 }"""

decodeString (maybe (field "age" int)) json == Ok (Just 42)
decodeString (maybe (field "name" int)) json == Ok Nothing
decodeString (maybe (field "height" float)) json == Ok Nothing

decodeString (field "age" (maybe int)) json == Ok (Just 42)
decodeString (field "name" (maybe int)) json == Ok Nothing
decodeString (field "height" (maybe float)) json == Err ...

Notice the last example! It is saying we *must* have a field named height and the content *may* be a float. There is no height field, so the decoder fails.

Point is, maybe will make exactly what it contains conditional. For optional fields, this means you probably want it *outside* a use of field or at.

oneOf

oneOf : List (Decoder a) -> Decoder a

Try a bunch of different decoders. This can be useful if the JSON may come in a couple different formats. For example, say you want to read an array of numbers, but some of them are null.

Examples

badInt : Decoder Int
badInt =
    oneOf [ int, null 0 ]

-- decodeString (list badInt) "[1,2,null,4]" == Ok [1,2,0,4]

map

map : (a -> b) -> Decoder a -> Decoder b

Transform a decoder. Maybe you just want to know the length of a string:

Examples

stringLength : Decoder Int
stringLength =
    map String.length string

It is often helpful to use map with oneOf, like when defining nullable:

nullable : Decoder a -> Decoder (Maybe a)
nullable decoder =
    oneOf
        [ null Nothing
        , map Just decoder
        ]

map2

map2 : (a -> b -> c) -> Decoder a -> Decoder b -> Decoder c

Try two decoders and then combine the result. We can use this to decode objects with many fields:

Examples

type alias Point =
    { x : Float
    , y : Float
    }

point : Decoder Point
point =
    map2 (\x y -> { x = x, y = y })
        (field "x" float)
        (field "y" float)

-- decodeString point """{ "x": 3, "y": 4 }""" == Ok { x = 3, y = 4 }

map3

map3 : (a -> b -> c -> value) -> Decoder a -> Decoder b -> Decoder c -> Decoder value

Try three decoders and then combine the result. We can use this to decode objects with many fields:

Examples

type alias Person =
    { name : String
    , age : Int
    , height : Float
    }

person : Decoder Person
person =
    map3 (\name age height -> { name = name, age = age, height = height })
        (at ["name"] string)
        (at ["info", "age"] int)
        (at ["info", "height"] float)

-- json = """{ "name": "tom", "info": { "age": 42, "height": 1.8 } }"""
-- decodeString person json == Ok { name = "tom", age = 42, height = 1.8 }

map4

map4 : (a -> b -> c -> d -> value) -> Decoder a -> Decoder b -> Decoder c -> Decoder d -> Decoder value

Try four decoders and then combine the result.

Examples

map4 (\a b c d -> (a, b, c, d))
    (index 0 int)
    (index 1 int)
    (index 2 int)
    (index 3 int)

-- decodeString ... "[1,2,3,4]" == Ok (1, 2, 3, 4)

map5

map5 : (a -> b -> c -> d -> e -> value) -> Decoder a -> Decoder b -> Decoder c -> Decoder d -> Decoder e -> Decoder value

Try five decoders and then combine the result.

Examples

map5 (\a b c d e -> (a, b, c, d, e))
    (index 0 int)
    (index 1 int)
    (index 2 int)
    (index 3 int)
    (index 4 int)

map6

map6 : (a -> b -> c -> d -> e -> f -> value) -> Decoder a -> Decoder b -> Decoder c -> Decoder d -> Decoder e -> Decoder f -> Decoder value

Try six decoders and then combine the result.

Examples

map6 (\a b c d e f -> (a, b, c, d, e, f))
    (field "a" int)
    (field "b" int)
    (field "c" int)
    (field "d" int)
    (field "e" int)
    (field "f" int)

map7

map7 : (a -> b -> c -> d -> e -> f -> g -> value) -> Decoder a -> Decoder b -> Decoder c -> Decoder d -> Decoder e -> Decoder f -> Decoder g -> Decoder value

Try seven decoders and then combine the result.

Examples

map7 (\a b c d e f g -> (a, b, c, d, e, f, g))
    (field "a" int)
    (field "b" int)
    (field "c" int)
    (field "d" int)
    (field "e" int)
    (field "f" int)
    (field "g" int)

map8

map8 : (a -> b -> c -> d -> e -> f -> g -> h -> value) -> Decoder a -> Decoder b -> Decoder c -> Decoder d -> Decoder e -> Decoder f -> Decoder g -> Decoder h -> Decoder value

Try eight decoders and then combine the result.

Examples

map8 (\a b c d e f g h -> (a, b, c, d, e, f, g, h))
    (field "a" int)
    (field "b" int)
    (field "c" int)
    (field "d" int)
    (field "e" int)
    (field "f" int)
    (field "g" int)
    (field "h" int)

lazy

lazy : (() -> Decoder a) -> Decoder a

Sometimes you have JSON with recursive structure, like nested comments. You can use lazy to make sure your decoder unrolls lazily.

Examples

type alias Comment =
    { message : String
    , responses : Responses
    }

type Responses
    = Responses (List Comment)

comment : Decoder Comment
comment =
    map2 (\message responses -> { message = message, responses = responses })
        (field "message" string)
        (field "responses" (map Responses (list (lazy (\_ -> comment)))))

If we had said list comment instead, we would start expanding the value infinitely. By using list (lazy (\_ -> comment)) we make sure the decoder only expands to be as deep as the JSON we are given.

value

value : Decoder Value

Do not do anything with a JSON value, just bring it into Selm as a Value.

Examples

decodeString value "42"
    |> Result.map Json.Encode.encode == Ok "42"

null

null : a -> Decoder a

Decode a null value into some Selm value.

Examples

decodeString (null False) "null" == Ok False
decodeString (null 42) "null" == Ok 42
decodeString (null 42) "42" == Err ...
decodeString (null 42) "false" == Err ...

succeed

succeed : a -> Decoder a

Ignore the JSON and produce a certain Selm value.

Examples

decodeString (succeed 42) "true" == Ok 42
decodeString (succeed 42) "[1,2,3]" == Ok 42
decodeString (succeed 42) "hello" == Err ...

This is handy when used with oneOf or andThen.

fail

fail : String -> Decoder a

Ignore the JSON and make the decoder fail. This is handy when used with oneOf or andThen where you want to give a custom error message in some case.

Examples

decodeString (fail "bad input") "42" == Err ...

See the andThen docs for another example.

andThen

andThen : (a -> Decoder b) -> Decoder a -> Decoder b

Create decoders that depend on previous results. If you are creating versioned data, you might do something like this:

Examples

info : Decoder Info
info =
    field "version" int
        |> andThen infoHelp

infoHelp : Int -> Decoder Info
infoHelp version =
    case version of
        4 ->
            infoDecoder4

        3 ->
            infoDecoder3

        _ ->
            fail <|
                "Trying to decode info, but version "
                    ++ String.fromInt version
                    ++ " is not supported."