Skip to content

Commit

Permalink
Merge pull request #32 from imclerran/add-option-example
Browse files Browse the repository at this point in the history
Add example of encoding object Using OptionOrNull
  • Loading branch information
lukewilliamboswell committed May 13, 2024
2 parents 96c036f + 40eccd5 commit 9dd2190
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
17 changes: 17 additions & 0 deletions ci/expect_scripts/optional.exp
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#!/usr/bin/expect

# uncomment line below for debugging
# exp_internal 1

set timeout 7

spawn ./examples/optional


expect "{\"firstName\":\"Luke\",}\r\n{\"firstName\":\"Luke\",\"lastName\":null}\r\n{\"firstName\":\"Luke\",\"lastName\":null}\r\n{\"firstName\":\"Luke\",\"lastName\":\"Boswell\"}" {
expect eof
exit 0
}

puts stderr "\nError: output was different from expected value."
exit 1
37 changes: 37 additions & 0 deletions examples/optional.roc
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
app [main] {
cli: platform "https://github.com/roc-lang/basic-cli/releases/download/0.10.0/vNe6s9hWzoTZtFmNkvEICPErI9ptji_ySjicO6CkucY.tar.br",
json: "../package/main.roc", # use release URL (ends in tar.br) for local example, see github.com/lukewilliamboswell/roc-json/releases
}

import cli.Stdout
import cli.Task
import json.Json
import json.OptionOrNull exposing [OptionOrNull]

Object : { firstName: Str, lastName: OptionOrNull Str }

main =
noneObj : Object
noneObj = { firstName: "Luke", lastName: OptionOrNull.none {} }
nullObj : Object
nullObj = { firstName: "Luke", lastName: OptionOrNull.null {} }
someObj : Object
someObj = { firstName: "Luke", lastName: OptionOrNull.some "Boswell" }

# noneJson == {"firstName":"Luke",}
noneJson = Encode.toBytes noneObj (Json.utf8With { emptyEncodeAsNull: Json.encodeAsNullOption { record: Bool.false } })
Stdout.line! (noneJson |> Str.fromUtf8 |> Result.withDefault "Failed to encode JSON")

# nullNoneJson == {"firstName":"Luke","lastName":null}
nullNoneJson = Encode.toBytes noneObj (Json.utf8With { emptyEncodeAsNull: Json.encodeAsNullOption { record: Bool.true } })
Stdout.line! (nullNoneJson |> Str.fromUtf8 |> Result.withDefault "Failed to encode JSON")

# nullJson == {"firstName":"Luke","lastName":null}
nullJson = Encode.toBytes nullObj Json.utf8
Stdout.line! (nullJson |> Str.fromUtf8 |> Result.withDefault "Failed to encode JSON")

# someJson == {"firstName":"Luke","lastName":"Boswell"}
someJson = Encode.toBytes someObj Json.utf8
Stdout.line (someJson |> Str.fromUtf8 |> Result.withDefault "Failed to encode JSON")


0 comments on commit 9dd2190

Please sign in to comment.