FSharp.Json


Tutorial

Encoder

1: 
2: 
3: 
4: 
5: 
6: 
7: 
8: 
9: 
open FSharp.Json.Encode

let json =
    encode true <|
        jobject [
            "foo", jstring "bar"
            "age", jint 42
            "list", jlist (List.map jint [ 1..10 ])
        ]
No value has been returned

Decoder

Decode a Record

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
open FSharp.Json.Decode

type Record =
    { prop1: string
      prop2: int
      prop3: bool }

let record =
    decodeString
        (object3 (fun p1 p2 p3 -> { prop1 = p1; prop2 = p2; prop3 = p3 })
                 ("prop1" := dstring)
                 ("prop2" := dint)
                 ("prop3" := dbool))
        "{ \"prop1\": \"hello\", \"prop2\": 42, \"prop3\": false }"
No value has been returned

Decode a discriminated Union

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
open FSharp.Json.Decode

type Shape =
    | Rectangle of float * float
    | Circle of float

let shapeInfo tag =
    match tag with
    | "rectangle" ->
        object2 (fun w h -> Rectangle(w, h))
                ("width" := dfloat)
                ("height" := dfloat)
    | "circle" ->
        object1 Circle ("radius" := dfloat)
    | _ -> fail (tag + " is not a recognized tag for shape")

let shape =
    ("tag" := dstring) >>= shapeInfo

Rectangle

1: 
2: 
3: 
4: 
let rectangle =
    decodeString
        shape
        """{ "tag": "rectangle", "width": 100, "height": 40 }"""
No value has been returned

Circle

1: 
2: 
3: 
4: 
let circle =
    decodeString
        shape
        """{ "tag": "circle", "radius": 90 }"""
No value has been returned

Bad

1: 
2: 
3: 
4: 
let bad =
    decodeString
        shape
        """{ "tag": "other" }"""
No value has been returned

Decode oddly shaped values

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
open FSharp.Json.Decode

type Person =
    { name: string
      age: int
      profession: string option }

let dperson =
    object3 (fun n a p -> { name = n; age = a; profession = p })
            ("name" := dstring)
            ("age" := dint)
            (maybe ("profession" := dstring))

Profession: Some "plumber"

1: 
let tom = decodeString dperson """{ "name": "Tom", "age": 31, "profession": "plumber" }"""
No value has been returned

Profession: None

1: 
2: 
3: 
let sue = decodeString dperson """{ "name": "Sue", "age": 42 }"""
let amy = decodeString dperson """{ "name": "Amy", "age": 27, "profession": null }"""
let joe = decodeString dperson """{ "name": "Joe", "age": 36, "profession": ["something", "unexpected"] }"""
No value has been returned
No value has been returned
No value has been returned
Fork me on GitHub