• Stars
    star
    195
  • Rank 192,149 (Top 4 %)
  • Language
    F#
  • License
    Apache License 2.0
  • Created over 10 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Json mapper for F#

Fleece

Fleece is a JSON mapper for F#. It simplifies mapping from a Json library's JsonValue onto your types, and mapping from your types onto JsonValue.

The Json library could be System.Json, System.Text.Json, FSharp.Data's or NewtonSoft's Json.NET.

Its design is strongly influenced by Haskell's Aeson. Like Aeson, Fleece is designed around two typeclasses (in FSharpPlus style) ToJson and OfJson.

Download binaries

Example

For example, given this data type:

type Person = {
    Name: string
    Age: int
    Children: Person list
}

You can map it to JSON like this:

open Fleece
open Fleece.Operators

type Person with
    static member ToJson (x: Person) =
        jobj [ 
            "name" .= x.Name
            "age" .= x.Age
            "children" .= x.Children
        ]

let p = 
    { Person.Name = "John"
      Age = 44
      Children = 
      [
        { Person.Name = "Katy"
          Age = 5
          Children = [] }
        { Person.Name = "Johnny"
          Age = 7
          Children = [] }
      ] }

// Test with System.Text.Json

open Fleece.SystemTextJson
printfn "%s" (toJsonText p)

And you can map it from JSON like this:

type Person with
    static member OfJson json =
        match json with
        | JObject o ->
            let name = o .@ "name"
            let age = o .@ "age"
            let children = o .@ "children"
            match name, age, children with
            | Decode.Success name, Decode.Success age, Decode.Success children ->
                Decode.Success {
                    Person.Name = name
                    Age = age
                    Children = children
                }
            | x -> Error <| Uncategorized (sprintf "Error parsing person: %A" x)
        | x -> Decode.Fail.objExpected x
        
let john : Person ParseResult = ofJsonText """{"name": "John", "age": 44, "children": [{"name": "Katy", "age": 5, "children": []}, {"name": "Johnny", "age": 7, "children": []}]}"""

Though it's much easier to do this in a monadic or applicative way. For example, using FSharpPlus (which is already a dependency of Fleece):

open FSharpPlus

type Person with
    static member Create name age children = { Person.Name = name; Age = age; Children = children }

    static member OfJson json =
        match json with
        | JObject o -> Person.Create <!> (o .@ "name") <*> (o .@ "age") <*> (o .@ "children")
        | x -> Decode.Fail.objExpected x

or with applicatives:

open FSharpPlus

type Person with
    static member OfJson json =
        match json with
        | JObject o -> 
            monad {
                let! name = o .@ "name"
                and! age = o .@ "age"
                and! children = o .@ "children"
                return {
                    Person.Name = name
                    Age = age
                    Children = children
                }
            }
        | x -> Decode.Fail.objExpected x

Or you can use the Choice monad/applicative in FSharpx.Extras instead, if you prefer.

You can see more examples in the EdmundsNet project.

CODEC

For types that deserialize to Json Objets, typically (but not limited to) records, you can alternatively use codecs and have a single method which maps between fields and values.

type Person = { 
    name : string * string
    age : int option
    children: Person list } 
    with
    static member get_Codec () =
        fun f l a c -> { name = (f, l); age = a; children = c }
        <!> jreq "firstName" (Some << fun x -> fst x.name)
        <*> jreq "lastName"  (Some << fun x -> snd x.name)
        <*> jopt "age"       (fun x -> x.age) // Optional fields can use 'jopt'
        <*> jreq "children"  (fun x -> Some x.children)
        |> ofObjCodec
        
let john: Person ParseResult = ofJsonText """{"name": "John", "age": 44, "children": [{"name": "Katy", "age": 5, "children": []}, {"name": "Johnny", "age": 7, "children": []}]}"""

Discriminated unions can be modeled with alternatives:

type Shape =
    | Rectangle of width : float * length : float
    | Circle of radius : float
    | Prism of width : float * float * height : float
    with 
        static member get_Codec () =
            (Rectangle  <!> jreq "rectangle" (function Rectangle (x, y) -> Some (x, y) | _ -> None))
            <|> (Circle <!> jreq "radius"    (function Circle x -> Some x | _ -> None))
            <|> (Prism  <!> jreq "prism"     (function Prism (x, y, z) -> Some (x, y, z) | _ -> None))
            |> ofObjCodec

or using the jchoice combinator:

type Shape with
        static member JsonObjCodec =
            jchoice
                [
                    Rectangle <!> jreq "rectangle" (function Rectangle (x, y) -> Some (x, y) | _ -> None)
                    Circle    <!> jreq "radius"    (function Circle x -> Some x | _ -> None)
                    Prism     <!> jreq "prism"     (function Prism (x, y, z) -> Some (x, y, z) | _ -> None)
                ]
             |> ofObjCodec

But codecs for both types can easily be written with the codec computation expressions

type Person = { 
    name : string * string
    age : int option
    children: Person list } 
    with
        static member get_Codec () =
            codec {
                let! f = jreq "firstName" (Some << fun x -> fst x.name)
                and! l = jreq "lastName"  (Some << fun x -> snd x.name)
                and! a = jopt "age"       (fun x -> x.age) // Optional fields can use 'jopt'
                and! c = jreq "children"  (fun x -> Some x.children)
                return { name = (f, l); age = a; children = c } }
            |> ofObjCodec
        

type Shape =
    | Rectangle of width : float * length : float
    | Circle of radius : float
    | Prism of width : float * float * height : float
    with
        static member get_Codec () =
            codec {
                Rectangle <!> jreq "rectangle" (function Rectangle (x, y) -> Some (x, y) | _ -> None)
                Circle    <!> jreq "radius"    (function Circle x -> Some x | _ -> None)
                Prism     <!> jreq "prism"     (function Prism (x, y, z) -> Some (x, y, z) | _ -> None)
            }
            |> ofObjCodec

What's happening here is that we're getting a Codec to/from a Json Object (not neccesarily a JsonValue) which Fleece is able to take it and fill the gap by composing it with a codec from JsonObject to/from JsonValue.

We can also do that by hand, we can manipulate codecs by using functions in the Codec module. Here's an example:

open System.Text
open Fleece.SystemTextJson.Operators

type Person = { 
    name : string * string
    age : int option
    children: Person list } 
    with
        static member JsonObjCodec: Codec<PropertyList<Fleece.SystemTextJson.Encoding>, Person> = codec {
            let! f = jreq "firstName" (Some << fun x -> fst x.name)
            and! l = jreq "lastName"  (Some << fun x -> snd x.name)
            and! a = jopt "age"       (fun x -> x.age) // Optional fields can use 'jopt'
            and! c = jreq "children"  (fun x -> Some x.children)
            return { name = (f, l); age = a; children = c } }

let personBytesCodec =
    Person.JsonObjCodec
    |> Codec.compose jsonObjToValueCodec    // this is the codec that fills the gap to/from JsonValue
    |> Codec.compose jsonValueToTextCodec   // this is a codec between JsonValue and JsonText
    |> Codec.invmap (Encoding.UTF8.GetString: byte [] -> string) Encoding.UTF8.GetBytes    // This is a pair of of isomorphic functions

let p = { name = "John", "Smith"; age = Some 42; children = [] }


let bytePerson = Codec.encode personBytesCodec p
// val bytePerson : byte [] = [|123uy; 34uy; 102uy; 105uy; 114uy; 115uy; ... |]
let p' = Codec.decode personBytesCodec bytePerson

Combinators

So far we've seen how Fleece is capable of encoding/decoding by deriving automatically a codec from static members in the type.

But for those cases where we don't have control over the types (extension members won't be taken into account) we can explicitly specify combinators.

To do so, a set of the available functions exists, ending with the With suffix, which accepts a combinator as first parameter:

type Color = Red | Blue | White

type Car = {
    Id : string
    Color : Color
    Kms : int }

let colorDecoder = function
    | JString "red"   -> Decode.Success Red  
    | JString "blue"  -> Decode.Success Blue 
    | JString "white" -> Decode.Success White
    | JString  x as v -> Decode.Fail.invalidValue v ("Wrong color: " + x)
    | x               -> Decode.Fail.strExpected  x

let colorEncoder = function
    | Red   -> JString "red"
    | Blue  -> JString "blue"
    | White -> JString "white"

let colorCodec () = colorDecoder <-> colorEncoder
    
let carCodec () =
    codec {
        let! i = jreqWith Codecs.string "id"    (fun x -> Some x.Id)
        and! c = jreqWith colorCodec    "color" (fun x -> Some x.Color)
        and! k = jreqWith Codecs.int    "kms"   (fun x -> Some x.Kms)
        return { Id = i; Color = c; Kms = k }
    }
    |> Codec.compose (Codecs.propList Codecs.id)

let car = { Id = "xyz"; Color = Red; Kms = 0 }

let jsonCar : Fleece.SystemTextJson.Encoding = Codec.encode (carCodec ()) car
// val jsonCar: SystemTextJson.Encoding = {"id":"xyz","color":"red","kms":0}

Json Lenses

Json lenses allow to focus on a specific part of the json structure to perform operations like view, write and update.

For a quick reference have a look at this test file

Maintainer(s)

More Repositories

1

Paket

A dependency manager for .NET with support for NuGet packages and Git repositories.
F#
1,987
star
2

FAKE

FAKE - F# Make
F#
1,273
star
3

awesome-fsharp

A curated list of awesome F# frameworks, libraries, software and resources.
1,142
star
4

Avalonia.FuncUI

Develop cross-plattform GUI Applications using F# and Avalonia!
F#
841
star
5

FSharpPlus

Extensions for F#
F#
821
star
6

FSharp.Data

F# Data: Library for Data Access
F#
803
star
7

fantomas

FSharp source code formatter
F#
742
star
8

FSharpx.Extras

Functional programming and other utilities from the original "fsharpx" project
F#
676
star
9

Rezoom.SQL

Statically typechecks a common SQL dialect and translates it to various RDBMS backends
F#
665
star
10

SQLProvider

A general F# SQL database erasing type provider, supporting LINQ queries, schema exploration, individuals, CRUD operations and much more besides.
F#
558
star
11

ProjectScaffold

A prototypical .NET solution (file system layout and tooling), recommended for F# projects
F#
514
star
12

FSharp.Formatting

F# tools for generating documentation (Markdown processor and F# code formatter)
F#
455
star
13

IfSharp

F# for Jupyter Notebooks
Jupyter Notebook
441
star
14

Argu

A declarative CLI argument parser for F#
F#
433
star
15

FsHttp

A lightweight F# HTTP library by @SchlenkR and @dawedawe
F#
413
star
16

FsUnit

FsUnit makes unit-testing with F# more enjoyable. It adds a special syntax to your favorite .NET testing framework.
F#
413
star
17

FSharp.Data.GraphQL

FSharp implementation of Facebook GraphQL query language.
F#
393
star
18

fsharp-companies

Community curated list of companies that use F#
370
star
19

fsharp-cheatsheet

This cheatsheet aims to succinctly cover the most important aspects of F# 6.0.
F#
319
star
20

zarchive-fsharpbinding

Archive of F# Language Bindings for Open Editors
Emacs Lisp
307
star
21

FSharpLint

Lint tool for F#
F#
297
star
22

FSharp.TypeProviders.SDK

The SDK for creating F# type providers
F#
296
star
23

pulsar-client-dotnet

Apache Pulsar native client for .NET (C#/F#/VB)
F#
288
star
24

FSharp.Control.Reactive

Extensions and wrappers for using Reactive Extensions (Rx) with F#.
F#
283
star
25

FsReveal

FsReveal parses markdown and F# script file and generates reveal.js slides.
F#
257
star
26

SwaggerProvider

F# generative Type Provider for Swagger
F#
257
star
27

FSharpx.Collections

FSharpx.Collections is a collection of datastructures for use with F# and C#.
F#
244
star
28

FSharp.Data.Adaptive

On-demand adaptive/incremental data for F# https://fsprojects.github.io/FSharp.Data.Adaptive/
F#
241
star
29

FSharp.Json

F# JSON Reflection based serialization library
F#
218
star
30

fsharp-language-server

F#
215
star
31

fsharp-ai-tools

TensorFlow API for F# + F# for AI Models eDSL
F#
212
star
32

FSharp.Data.SqlClient

A set of F# Type Providers for statically typed access to MS SQL database
F#
207
star
33

FsLexYacc

Lexer and parser generators for F#
F#
201
star
34

Chessie

Railway-oriented programming for .NET
F#
189
star
35

ExcelFinancialFunctions

.NET Standard library providing the full set of financial functions from Excel.
F#
187
star
36

FsXaml

F# Tools for working with XAML Projects
F#
171
star
37

FSharp.Control.AsyncSeq

Asynchronous sequences for F#
F#
159
star
38

FSharp.UMX

F# units of measure for primitive non-numeric types
F#
150
star
39

Paket.VisualStudio

Manage your Paket (http://fsprojects.github.io/Paket/) dependencies from Visual Studio!
C#
148
star
40

ExcelProvider

This library is for the .NET platform implementing a Excel type provider.
F#
139
star
41

FsBlog

Blog aware, static site generation using F#.
CSS
133
star
42

TickSpec

Lean .NET BDD framework with powerful F# integration
F#
131
star
43

SIMDArray

SIMD enhanced Array operations
F#
128
star
44

FSharp.Configuration

The FSharp.Configuration project contains type providers for the configuration of .NET projects.
F#
115
star
45

FSharp.Interop.Dynamic

DLR interop for F# -- works like dynamic keyword in C#
F#
93
star
46

FSharpx.Async

Asynchronous programming utilities for F#
F#
93
star
47

FSharp.Management

The FSharp.Management project contains various type providers for the management of the machine.
F#
89
star
48

FSharp.Control.TaskSeq

A computation expression and module for seamless working with IAsyncEnumerable<'T> as if it is just another sequence
F#
83
star
49

AzureStorageTypeProvider

An F# Azure Type Provider which can be used to explore Blob, Table and Queue Azure Storage assets and easily apply CRUD operations on them.
F#
83
star
50

Foq

A unit testing framework for F#
F#
78
star
51

FSharp.Azure.Storage

F# API for using Microsoft Azure Table Storage service
F#
75
star
52

FSharp.ViewModule

Library providing MVVM and INotifyPropertyChanged support for F# projects
F#
74
star
53

FSharp.Text.RegexProvider

A type provider for regular expressions.
F#
73
star
54

FSharp.Core.Fluent

Fluent members for F# FSharp.Core functions
F#
71
star
55

Mechanic

F#
68
star
56

Incremental.NET

A library for incremental computations. Based on janestreet/incremental (https://github.com/janestreet/incremental) for OCaml.
F#
67
star
57

FSharp.Collections.ParallelSeq

Parallel (multi-core) sequence operations
F#
67
star
58

FSharp.Quotations.Evaluator

A quotations evaluator/compiler for F# based on LINQ expression tree compilation
F#
67
star
59

FSharp.Linq.ComposableQuery

Compositional Query Framework for F# Queries, based on "A Practical Theory of Language-Integrated Query"
F#
67
star
60

OpenAPITypeProvider

F# type provider for Open API specification
F#
65
star
61

FSharp.Data.Toolbox

F# Data-based library for various data access APIs
F#
57
star
62

FSharp.AWS.DynamoDB

F# wrapper API for AWS DynamoDB
F#
56
star
63

DynamoDb.SQL

SQL-like external DSL for querying and scanning Amazon DynamoDB
F#
54
star
64

fsharp-hashcollections

Library providing fast hash based immutable map and set
F#
53
star
65

FsRandom

A purely-functional random number generator framework designed for F#
F#
51
star
66

Z3Fs

Simple DSL to solve SMT problems using Z3 API in F#
F#
51
star
67

FSharp.Data.JsonSchema

F#
49
star
68

SyntacticVersioning

Helper tool to verify semantic version changes based on API surface area changes
F#
46
star
69

fantomas-for-vs

Visual Studio Formatter for F#
HTML
45
star
70

FSharp.Compatibility

Compatibility libraries for F#
F#
44
star
71

Interstellar

Cross-platform desktop apps in F# using web tech - https://www.nuget.org/packages/Interstellar.Core/
F#
42
star
72

FSharp.Compiler.PortaCode

The PortaCode F# code format and corresponding interpreter. Used by Fabulous and others.
F#
42
star
73

FSharp.Interop.PythonProvider

Early experimental F# type provider for python
F#
41
star
74

FSharp.CloudAgent

Allows running F# Agents in a distributed manner using Azure Service Bus.
F#
39
star
75

FSharp.Data.TypeProviders

F# Type Providers for SqlDataConnection, SqlEntityConnection, ODataService, WsdlService and EdmxFile using .NET Framework generators
F#
38
star
76

Roslyn.FSharp

Roslyn read-only API to work with F# code (via bridge to FSharp.Compiler.Service)
F#
36
star
77

FnuPlot

An F# wrapper for gnuplot charting library
F#
35
star
78

GraphProvider

A state machine type provider
F#
35
star
79

fantomas-tools

Collection of tools used when developing for Fantomas
F#
34
star
80

LocSta

An F# library for composing state-aware functions by @SchlenkR
JavaScript
33
star
81

fsharp-linting-for-vs

Visual Studio Linter for F#
C#
33
star
82

FSharp.Span.Utils

Makes Span/ReadOnlySpan easy to use from F#.
F#
33
star
83

FSharp.Data.Xsd

XML Type Provider with schema support
F#
32
star
84

zarchive-sublime-fsharp-package

F# development tools for SublimeText 3
Python
32
star
85

.github

The place to request for projects to be added or removed from the incubation space
28
star
86

Zander

Regular expression for matrix information. I.e. parse structured blocks of information from csv or excel files (or similar 2d matrixes)
F#
27
star
87

zarchive-xamarin-monodevelop-fsharp-addin

(No longer Used) F# Editing Support In MonoDevelop and Xamarin Studio
F#
27
star
88

FSharp.Compiler.CodeDom

An F# CodeDOM implementation (based on the old F# Power Pack)
F#
25
star
89

FsMath3D

F# 3D Math Library for realtime applications
F#
22
star
90

S3Provider

Experimental type provider for Amazon S3
F#
22
star
91

BioProviders

F# library for accessing and manipulating bioinformatic datasets.
F#
22
star
92

ReasoningEngine

Symbolic analysis of discrete dynamical systems
F#
22
star
93

FSharp.Data.WsdlProvider

An implementation of the WsdlProvider compatible with netfx and netcore
F#
22
star
94

FSharpPerf

A set of performance test scripts for the F# compiler.
F#
20
star
95

MarkerClustering

A component to cluster map markers.
F#
19
star
96

DynamicsCRMProvider

A type provider for Microsoft Dynamics CRM 2011.
F#
16
star
97

Amazon.SimpleWorkflow.Extensions

Extensions to AmazonSDK's SimpleWorkflow capabilities to make it more intuitive to use
F#
16
star
98

Canopy.Mobile

Canopy testing framework for mobile apps
F#
14
star
99

LSON

Lisp inspired serialization (intended for when you don't even want to take a dependency on JSON serializer)
F#
14
star
100

FSharp.Codecs.Redis

FSharp redis codecs based on Fleece patterns
F#
13
star