Library for turning Elm values into Json values.
encode : Basics.Int -> Value -> String
Convert a Value
into a prettified string. The first argument specifies
the amount of indentation in the resulting string.
import Json.Encode as Encode
tom : Encode.Value
tom =
Encode.object
[ ( "name", Encode.string "Tom" )
, ( "age", Encode.int 42 )
]
compact = Encode.encode 0 tom
-- {"name":"Tom","age":42}
readable = Encode.encode 4 tom
-- {
-- "name": "Tom",
-- "age": 42
-- }
Represents a JavaScript value.
string : String -> Value
Turn a String
into a JSON string.
import Json.Encode exposing (encode, string)
-- encode 0 (string "") == "\"\""
-- encode 0 (string "abc") == "\"abc\""
-- encode 0 (string "hello") == "\"hello\""
int : Basics.Int -> Value
Turn an Int
into a JSON number.
import Json.Encode exposing (encode, int)
-- encode 0 (int 42) == "42"
-- encode 0 (int -7) == "-7"
-- encode 0 (int 0) == "0"
float : Basics.Float -> Value
Turn a Float
into a JSON number.
import Json.Encode exposing (encode, float)
-- encode 0 (float 3.14) == "3.14"
-- encode 0 (float 1.618) == "1.618"
-- encode 0 (float -42) == "-42"
-- encode 0 (float NaN) == "null"
-- encode 0 (float Infinity) == "null"
Note: Floating point numbers are defined in the IEEE 754 standard
which is hardcoded into almost all CPUs. This standard allows Infinity
and
NaN
. The JSON spec does not include these values, so we encode them
both as null
.
bool : Basics.Bool -> Value
Turn a Bool
into a JSON boolean.
import Json.Encode exposing (encode, bool)
-- encode 0 (bool True) == "true"
-- encode 0 (bool False) == "false"
null : Value
Create a JSON null
value.
import Json.Encode exposing (encode, null)
-- encode 0 null == "null"
list : (a -> Value) -> List a -> Value
Turn a List
into a JSON array.
import Json.Encode as Encode exposing (bool, encode, int, list, string)
-- encode 0 (list int [1,3,4]) == "[1,3,4]"
-- encode 0 (list bool [True,False]) == "[true,false]"
-- encode 0 (list string ["a","b"]) == """["a","b"]"""
array : (a -> Value) -> Array a -> Value
Turn an Array
into a JSON array.
set : (a -> Value) -> Set a -> Value
Turn an Set
into a JSON array.
object : List ( String, Value ) -> Value
Create a JSON object.
import Json.Encode as Encode
tom : Encode.Value
tom =
Encode.object
[ ( "name", Encode.string "Tom" )
, ( "age", Encode.int 42 )
]
-- Encode.encode 0 tom == """{"name":"Tom","age":42}"""
dict : (k -> String) -> (v -> Value) -> Dict k v -> Value
Turn a Dict
into a JSON object.
import Dict exposing (Dict)
import Json.Encode as Encode
people : Dict String Int
people =
Dict.fromList [ ("Tom",42), ("Sue", 38) ]
-- Encode.encode 0 (Encode.dict identity Encode.int people)
-- == """{"Tom":42,"Sue":38}"""