Skip to content

Instantly share code, notes, and snippets.

@honewatson
Created June 7, 2018 22:49
Show Gist options
  • Save honewatson/97cf5d52b54ed31423afbc41b45c9214 to your computer and use it in GitHub Desktop.
Save honewatson/97cf5d52b54ed31423afbc41b45c9214 to your computer and use it in GitHub Desktop.
Nim Json
import json
import marshal
import options
type
Message = object
id: int
message: string
OptionalMessage = object
id: int
message: Option[string]
var message = Message(message: "Hello", id: 1)
echo $$message # Marshal can just serialize a type to JSON
# -> {"id": 1, "message": "Hello"}
var messages = @[message]
echo $$messages
# -> [{"id": 1, "message": "Hello"}]
var optMessage = OptionalMessage(id: 1, message: some("hello"))
echo $$optMessage
# -> {"id": 1, "message": {"val": "hello", "has": true}}
converter toMessage(message: OptionalMessage): Message =
result = Message(id: message.id, message: get(message.message, ""))
echo $$toMessage(optMessage)
# -> {"id": 1, "message": "hello"}
try:
# will raise the first key error it finds in the order
# of declared object properties but not others
echo $to(parseJson("""{ "bobo": "chimp" }"""), Message)
except:
echo getCurrentExceptionMsg()
try:
# will still raise id error
echo $to(parseJson("""{ "message": "chimp" }"""), Message)
except:
echo getCurrentExceptionMsg()
# key not found: id
try:
echo $to(parseJson("""{ "id": "chimp" }"""), Message)
except:
echo getCurrentExceptionMsg()
# key not found: id
echo $to(parseJson("""{ "id": 1 }"""), OptionalMessage)
# -> OptionalMessage(id: 1, message: None[string])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment