F# JSON
last modified December 4, 2026
In this article we convert F# values to JSON and back with
System.Text.Json.
JSON (JavaScript Object Notation) is a text format for structured data.
It has objects with named properties, arrays, strings, numbers, Booleans,
and null. Web services, configuration files, and many tools
use it. System.Text.Json is part of .NET, so scripts and
projects can use it without a package. It handles F# records, lists,
options, and maps; since .NET 11 it also handles discriminated unions.
Serializing a record
Serialization turns a value into JSON text.
JsonSerializer.Serialize writes each field of a record as a
property of a JSON object.
open System.Text.Json
type Book = { Title: string; Author: string; Year: int }
let book = { Title = "Solaris"; Author = "Stanislaw Lem"; Year = 1961 }
let json = JsonSerializer.Serialize book
printfn "%s" json
The property names are the field names, and the result is compact: one line without spaces.
λ dotnet fsi serialize.fsx
{"Title":"Solaris","Author":"Stanislaw Lem","Year":1961}
Indentation and camel case
A JsonSerializerOptions object changes the output.
WriteIndented puts each property on its own line, and a
naming policy renames the properties. JSON usually uses camel case
(firstName), while F# record fields use Pascal case
(FirstName).
open System.Text.Json
type Book = { Title: string; Author: string; Year: int }
let books =
[ { Title = "Solaris"; Author = "Stanislaw Lem"; Year = 1961 }
{ Title = "Roadside Picnic"; Author = "Strugatsky brothers"; Year = 1972 } ]
let options =
JsonSerializerOptions(WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase)
printfn "%s" (JsonSerializer.Serialize(books, options))
The options are set with named arguments in the constructor call. An F# list becomes a JSON array. Creating options is relatively expensive, because the serializer caches type information in them, so we create them once and reuse them.
λ dotnet fsi options.fsx
[
{
"title": "Solaris",
"author": "Stanislaw Lem",
"year": 1961
},
{
"title": "Roadside Picnic",
"author": "Strugatsky brothers",
"year": 1972
}
]
Deserializing
Deserialization turns JSON text back into a value.
JsonSerializer.Deserialize needs the target type as a type
argument.
open System.Text.Json
type Book = { Title: string; Author: string; Year: int }
let json = """{"Title":"Solaris","Author":"Stanislaw Lem","Year":1961}"""
let book = JsonSerializer.Deserialize<Book> json
printfn "%A" book
printfn "%s was written in %d" book.Title book.Year
let again = JsonSerializer.Deserialize<Book>(JsonSerializer.Serialize book)
printfn "same value: %b" (again = book)
The record is created through its constructor, with the values of the matching JSON properties. A round trip through JSON gives a record that is equal to the original.
let json = """{"Title":"Solaris","Author":"Stanislaw Lem","Year":1961}"""
Triple-quoted strings may contain double quotes, which makes them handy for JSON in code.
λ dotnet fsi deserialize.fsx
{ Title = "Solaris"
Author = "Stanislaw Lem"
Year = 1961 }
Solaris was written in 1961
same value: true
Lists, options, and maps
Records may contain other F# types. Each has a natural JSON form.
open System.Text.Json
type Film =
{ Title: string
Genres: string list
Sequel: string option
Ratings: Map<string, float> }
let films =
[ { Title = "Alien"; Genres = [ "horror"; "sci-fi" ]; Sequel = Some "Aliens"
Ratings = Map [ "imdb", 8.5; "critics", 9.3 ] }
{ Title = "Amadeus"; Genres = [ "drama" ]; Sequel = None
Ratings = Map [ "imdb", 8.4; "critics", 8.9 ] } ]
let options = JsonSerializerOptions(WriteIndented = true)
let json = JsonSerializer.Serialize(films, options)
printfn "%s" json
let back = JsonSerializer.Deserialize<Film list> json
printfn "round trip equal: %b" (back = films)
A list is an array, Some is the value itself,
None is null, and a map with string keys is an
object. Map keys are written in sorted order. All of them come back from
deserialization as the same F# types.
λ dotnet fsi collections.fsx
[
{
"Title": "Alien",
"Genres": [
"horror",
"sci-fi"
],
"Sequel": "Aliens",
"Ratings": {
"critics": 9.3,
"imdb": 8.5
}
},
{
"Title": "Amadeus",
"Genres": [
"drama"
],
"Sequel": null,
"Ratings": {
"critics": 8.9,
"imdb": 8.4
}
}
]
round trip equal: true
Missing properties
By default the serializer does not require the JSON to contain every
field. Missing properties get the default value of their type, which
for strings and lists is null. This can break F# code that
assumes record fields are never null.
open System.Text.Json
type Book = { Title: string; Author: string; Year: int; Tags: string list }
let json = """{"Title":"Solaris","Pages":204}"""
let book = JsonSerializer.Deserialize<Book> json
printfn "%A" book
let strict = JsonSerializerOptions(RespectRequiredConstructorParameters = true)
try
JsonSerializer.Deserialize<Book>(json, strict) |> ignore
with :? JsonException as e ->
printfn "error: %s" e.Message
The Pages property has no matching field and is ignored.
Author and Tags are null and
Year is 0. With
RespectRequiredConstructorParameters, the parameters of the
record constructor become required, and a missing property throws a
JsonException.
λ dotnet fsi missing.fsx
{ Title = "Solaris"
Author = null
Year = 0
Tags = null }
error: JSON deserialization for type 'FSI_0001+Book' was missing required properties including: 'Author', 'Year', 'Tags'.
Invalid JSON
Malformed text and values of the wrong type also throw
JsonException. A small function turns the exception into a
Result, as shown in
F# Result type.
open System.Text.Json
type Point = { X: int; Y: int }
let parsePoint (json: string) =
try
Ok(JsonSerializer.Deserialize<Point> json)
with :? JsonException as e ->
Error e.Message
let inputs =
[ """{"X":3,"Y":4}"""
"""{"X":3,"Y":"four"}"""
"""{"X":3,"Y":4"""
"""[3,4]""" ]
for input in inputs do
match parsePoint input with
| Ok p -> printfn "ok: %d, %d" p.X p.Y
| Error msg -> printfn "error: %s" msg
The message gives the JSON path of the problem ($.Y is the
Y property of the root object) and its position in the
text. In scripts, type names get a prefix such as
FSI_0001+.
λ dotnet fsi invalid.fsx ok: 3, 4 error: The JSON value could not be converted to System.Int32. Path: $.Y | LineNumber: 0 | BytePositionInLine: 17. error: '4' is an invalid end of a number. Expected a delimiter. Path: $.Y | LineNumber: 0 | BytePositionInLine: 12. error: The JSON value could not be converted to FSI_0001+Point. Path: $ | LineNumber: 0 | BytePositionInLine: 1.
Property names
Attributes on record fields control single properties.
JsonPropertyName sets the name used in JSON and
JsonIgnore leaves a field out.
open System.Text.Json
open System.Text.Json.Serialization
type Account =
{ [<JsonPropertyName("user_name")>]
UserName: string
[<JsonPropertyName("created_at")>]
CreatedAt: System.DateOnly
[<JsonIgnore>]
Password: string }
let account =
{ UserName = "tomas"; CreatedAt = System.DateOnly(2026, 3, 14); Password = "s3cret" }
let json = JsonSerializer.Serialize account
printfn "%s" json
let back = JsonSerializer.Deserialize<Account> json
printfn "%A" back
The attributes are in System.Text.Json.Serialization. They
are useful when the JSON comes from a service that uses snake case.
DateOnly is written in the ISO 8601 format. The ignored
password is null after deserialization.
λ dotnet fsi attributes.fsx
{"user_name":"tomas","created_at":"2026-03-14"}
{ UserName = "tomas"
CreatedAt = 3/14/2026
Password = null }
Discriminated unions
Since .NET 11, System.Text.Json serializes
discriminated unions. In
earlier versions it threw NotSupportedException and
programs used the FSharp.SystemTextJson package instead.
open System.Text.Json
type Status =
| Open
| Closed
type Shape =
| Circle of radius: float
| Rect of width: float * height: float
type Ticket = { Id: int; Status: Status }
printfn "%s" (JsonSerializer.Serialize [ Open; Closed ])
printfn "%s" (JsonSerializer.Serialize({ Id = 7; Status = Closed }))
let shapes = [ Circle 1.5; Rect(2.0, 3.0) ]
let json = JsonSerializer.Serialize shapes
printfn "%s" json
let back = JsonSerializer.Deserialize<Shape list> json
printfn "%A" back
A case without fields is written as a string with its name. A case with
fields is an object: the $type property holds the case name
and the other properties hold the fields, named after the field labels.
printfn "%s" (JsonSerializer.Serialize({ Id = 7; Status = Closed }))
A record expression passed to a method needs parentheses around it; without them F# reports error FS0597.
λ dotnet fsi unions.fsx
["Open","Closed"]
{"Id":7,"Status":"Closed"}
[{"$type":"Circle","radius":1.5},{"$type":"Rect","width":2,"height":3}]
[Circle 1.5; Rect (2.0, 3.0)]
Reading unknown JSON
Sometimes we need only a few values from a large document, or its shape
is not known in advance. JsonNode.Parse reads JSON into a
tree of nodes that we navigate by property names and array indexes,
without defining types.
open System.Text.Json.Nodes
let json = """
{
"city": "Bratislava",
"current": { "temperature": 4.5, "wind": 12 },
"forecast": [
{ "day": "Mon", "high": 6 },
{ "day": "Tue", "high": 8 }
]
}
"""
let root = JsonNode.Parse json
let city = root["city"].GetValue<string>()
let temp = root["current"].["temperature"].GetValue<float>()
printfn "%s: %.1f °C" city temp
for day in root["forecast"].AsArray() do
printfn "%s %d" (day["day"].GetValue<string>()) (day["high"].GetValue<int>())
GetValue converts a value node to an F# type. To index the
result of an indexer we write .[ ] with a dot:
root["current"]["temperature"] is read as a function
applied to a list and gives error FS0597. AsArray gives a
sequence of the array items.
λ dotnet fsi nodes.fsx Bratislava: 4.5 °C Mon 6 Tue 8
Building JSON
JsonObject and JsonArray build a document piece
by piece, which suits data that does not have a fixed record type.
open System.Text.Json
open System.Text.Json.Nodes
let doc = JsonObject()
doc["name"] <- "build-report"
doc["passed"] <- true
let steps = JsonArray()
for name, seconds in [ "restore", 2.4; "build", 11.8; "test", 6.1 ] do
let step = JsonObject()
step["name"] <- name
step["seconds"] <- seconds
steps.Add step
doc["steps"] <- steps
doc["total"] <- 20.3
printfn "%s" (doc.ToJsonString(JsonSerializerOptions(WriteIndented = true)))
Strings, numbers, and Booleans convert to nodes when they are assigned.
ToJsonString writes the tree, with the same options as the
serializer.
λ dotnet fsi building.fsx
{
"name": "build-report",
"passed": true,
"steps": [
{
"name": "restore",
"seconds": 2.4
},
{
"name": "build",
"seconds": 11.8
},
{
"name": "test",
"seconds": 6.1
}
],
"total": 20.3
}
JSON files
Combined with the file functions from F# file I/O, serialization stores data between runs. The program keeps a to-do list in a file and adds one task on each run.
open System.IO
open System.Text.Json
type Todo = { Title: string; Done: bool }
let path = "todos.json"
let options = JsonSerializerOptions(WriteIndented = true)
let load () =
if File.Exists path then
JsonSerializer.Deserialize<Todo list>(File.ReadAllText path)
else
[]
let save (todos: Todo list) =
File.WriteAllText(path, JsonSerializer.Serialize(todos, options))
let todos = load ()
let added = todos @ [ { Title = $"task {todos.Length + 1}"; Done = false } ]
save added
printfn "tasks in the file: %d" added.Length
load returns an empty list when the file does not exist
yet. Each run reads the file, appends a task, and writes the file back.
We run it three times and print the file.
λ dotnet fsi todos.fsx
tasks in the file: 1
λ dotnet fsi todos.fsx
tasks in the file: 2
λ dotnet fsi todos.fsx
tasks in the file: 3
λ cat todos.json
[
{
"Title": "task 1",
"Done": false
},
{
"Title": "task 2",
"Done": false
},
{
"Title": "task 3",
"Done": false
}
]
Order summary
The last program reads orders from a JSON file in camel case, computes the totals per customer, and writes a summary file.
[
{ "id": 1, "customer": "Marta", "items": [ { "product": "pen", "price": 1.20, "qty": 10 } ] },
{ "id": 2, "customer": "Peter", "items": [ { "product": "lamp", "price": 24.90, "qty": 1 },
{ "product": "bulb", "price": 3.50, "qty": 4 } ] },
{ "id": 3, "customer": "Marta", "items": [ { "product": "paper", "price": 4.80, "qty": 2 } ] }
]
Each order has a customer and a list of items with a price and a quantity.
open System.IO
open System.Text.Json
type Item = { Product: string; Price: decimal; Qty: int }
type Order = { Id: int; Customer: string; Items: Item list }
type Summary = { Customer: string; Orders: int; Total: decimal }
let options =
JsonSerializerOptions(JsonSerializerDefaults.Web, WriteIndented = true)
let orders = JsonSerializer.Deserialize<Order list>(File.ReadAllText "orders.json", options)
let orderTotal (o: Order) =
o.Items |> List.sumBy (fun i -> i.Price * decimal i.Qty)
let summaries =
orders
|> List.groupBy (fun o -> o.Customer)
|> List.map (fun (customer, os) ->
{ Customer = customer
Orders = os.Length
Total = os |> List.sumBy orderTotal })
File.WriteAllText("summary.json", JsonSerializer.Serialize(summaries, options))
for s in summaries do
printfn "%-6s %d orders %8.2f" s.Customer s.Orders s.Total
JsonSerializerDefaults.Web creates options for web-style
JSON: camel case names and case-insensitive matching. We use
decimal for money; the serializer reads and writes it
without binary rounding errors. The summary records go to
summary.json.
λ dotnet fsi summary.fsx
Marta 2 orders 21.60
Peter 1 orders 38.90
λ cat summary.json
[
{
"customer": "Marta",
"orders": 2,
"total": 21.60
},
{
"customer": "Peter",
"orders": 1,
"total": 38.90
}
]
Source
JSON serialization and deserialization in .NET
Use a JSON DOM in System.Text.Json
In this article we have serialized and deserialized F# records, lists,
options, maps, and unions with System.Text.Json, changed the
output with options and attributes, handled missing properties and
invalid input, read and built documents with JsonNode, and
stored JSON in files. The next article,
F# HTTP client, reads JSON from web
services.
Author
List all F# tutorials.