Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New option for JSON serialization (#1482) #1485

Merged
merged 2 commits into from
Apr 30, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions src/FSharp.Data.Json.Core/JsonValue.fs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ type JsonSaveOptions =
/// Print the JsonValue in one line in a compact way
| DisableFormatting = 1

/// Print the JsonValue in one line in a compact way,
/// but place a single space after every comma
/// https://github.com/fsprojects/FSharp.Data/issues/1482
| CompactSpaceAfterComma = 2

/// Represents a JSON value. Large numbers that do not fit in the
/// Decimal type are represented using the Float case, while
/// smaller numbers are represented as decimals to avoid precision loss.
Expand Down Expand Up @@ -67,6 +72,13 @@ type JsonValue =

let propSep = if saveOptions = JsonSaveOptions.None then "\": " else "\":"

let comma () =
match saveOptions with
| JsonSaveOptions.None -> w.Write ","
| JsonSaveOptions.DisableFormatting -> w.Write ","
| JsonSaveOptions.CompactSpaceAfterComma -> w.Write ", "
| _ -> failwith "Invalid JsonSaveOptions"

let rec serialize indentation =
function
| Null -> w.Write "null"
Expand All @@ -83,7 +95,7 @@ type JsonValue =

for i = 0 to properties.Length - 1 do
let k, v = properties.[i]
if i > 0 then w.Write ","
if i > 0 then comma ()
newLine indentation 2
w.Write "\""
JsonValue.JsonStringEncodeTo w k
Expand All @@ -96,7 +108,7 @@ type JsonValue =
w.Write "["

for i = 0 to elements.Length - 1 do
if i > 0 then w.Write ","
if i > 0 then comma ()
newLine indentation 2
serialize (indentation + 2) elements.[i]

Expand Down