Created
November 16, 2023 23:12
-
-
Save Thorium/09a67ce08adee4fcc02ec7f0048e6962 to your computer and use it in GitHub Desktop.
Using Utf8JsonReader from System.Text.Json with FSharp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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