Json.Encode
Functions for turning Gren values into Json values.
encode :
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
[ { key = "name", value = Encode.string "Tom" }
, { key = "age", value = Encode.int 42 )
]
compact =
Encode.encode 0 tom
-- {"name":"Tom","age":42}
readable =
Encode.encode 4 tom
-- {
-- "name": "Tom",
-- "age": 42
-- }
type Value
Represents a JavaScript value.
Primitives
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 :
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 :
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 :
Bool -> Value
Turn a Bool into a JSON boolean.
import Json.Encode exposing (bool, encode)
-- 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"
Arrays
array :
(a -> Value) -> Array a -> Value
Turn a Array into a JSON array.
import Json.Encode as Encode exposing (array, bool, encode, int, string)
-- encode 0 (array int [1,3,4]) == "[1,3,4]"
-- encode 0 (array bool [True,False]) == "[true,false]"
-- encode 0 (array string ["a","b"]) == """["a","b"]"""
set :
(a -> Value) -> Set a -> Value
Turn an Set into a JSON array.
Objects
object :
Array { key : String, value : Value } -> Value
Create a JSON object.
import Json.Encode as Encode
tom : Encode.Value
tom =
Encode.object
[ { key = "name", value = Encode.string "Tom" }
, { key = "age", value = 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.fromArray [ { key = "Tom", value = 42 }, { key = "Sue", value = 38 } ]
-- Encode.encode 0 (Encode.dict identity Encode.int people)
-- == """{"Tom":42,"Sue":38}"""