diff --git a/ci/expect_scripts/optional.exp b/ci/expect_scripts/optional.exp new file mode 100644 index 0000000..28ff8c0 --- /dev/null +++ b/ci/expect_scripts/optional.exp @@ -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 \ No newline at end of file diff --git a/examples/optional.roc b/examples/optional.roc new file mode 100644 index 0000000..bc0e5f7 --- /dev/null +++ b/examples/optional.roc @@ -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") + +