Skip to content

Instantly share code, notes, and snippets.

@baronfel
Created March 29, 2022 22:05
Show Gist options
  • Save baronfel/3a8d95a03c20ea5a2c8bdc07048e69ce to your computer and use it in GitHub Desktop.
Save baronfel/3a8d95a03c20ea5a2c8bdc07048e69ce to your computer and use it in GitHub Desktop.
F# DU storage with FSharp.SystemTextJson
#r "nuget: FSharp.SystemTextJson, 0.17.4"
module Database =
open System.Text.Json.Serialization
open System.Text.Json
let options =
let o = JsonSerializerOptions()
o.Converters.Add(JsonFSharpConverter())
o
let private path = System.IO.Path.Combine(System.Environment.CurrentDirectory, "users.json")
let save data =
JsonSerializer.Serialize(data, options)
|> fun s -> System.IO.File.WriteAllText(path, s)
let load<'t> () =
JsonSerializer.Deserialize<'t>(System.IO.File.ReadAllText path, options)
type Person = { First: string; Last: string }
type Employee = Employee of person: Person | Manager of manager: Person * employees: Employee list
let chet = Employee { First = "Chet"; Last = "Husk"}
let tim = Manager ({ First = "Tim"; Last = "Heuer"}, [chet])
let data = Map.ofList [
"Chet", chet
"Tim", tim
]
Database.save data
let readData = Database.load ()
printfn "%b" (data = readData)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment