Skip to content

Instantly share code, notes, and snippets.

@Thorium
Created November 16, 2023 23:12
Show Gist options
  • Save Thorium/09a67ce08adee4fcc02ec7f0048e6962 to your computer and use it in GitHub Desktop.
Save Thorium/09a67ce08adee4fcc02ec7f0048e6962 to your computer and use it in GitHub Desktop.
Using Utf8JsonReader from System.Text.Json with FSharp
//High-performance JSON parsing with System.Text.Json and F#
// Example translated to F# from
// https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/use-utf8jsonreader
#r "nuget:System.Text.Json"
open System
open System.Text
open System.Text.Json
let options = JsonReaderOptions(
AllowTrailingCommas = true,
CommentHandling = JsonCommentHandling.Skip)
let readJson (jsonUtf8Bytes:ReadOnlySpan<byte>) =
let reader = Utf8JsonReader(jsonUtf8Bytes, options)
while reader.Read() do
Console.WriteLine reader.TokenType
match reader.TokenType with
| JsonTokenType.PropertyName
| JsonTokenType.String ->
let text = reader.GetString()
Console.Write " "
Console.Write text
| JsonTokenType.Number ->
let intValue = reader.GetInt32()
Console.Write " "
Console.Write intValue
| JsonTokenType.None | JsonTokenType.Null | JsonTokenType.Comment
| JsonTokenType.True | JsonTokenType.False
| JsonTokenType.StartObject | JsonTokenType.EndObject
| JsonTokenType.StartArray | JsonTokenType.EndArray
| _ -> () // Other token types elided for brevity
Console.WriteLine()
let sampleJson =
let jsonBytes =
"""{ "x": 3 }"""
|> Encoding.UTF8.GetBytes
readJson (System.ReadOnlySpan jsonBytes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment