Created
June 7, 2018 22:49
-
-
Save honewatson/97cf5d52b54ed31423afbc41b45c9214 to your computer and use it in GitHub Desktop.
Nim Json
This file contains hidden or 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
| 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