-
-
Save treeform/b9ae82d583773dc77fd214df45d5d20c to your computer and use it in GitHub Desktop.
This file contains 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 jsony, options | |
type | |
Bar = ref object | |
nameOfThing: string | |
arr: seq[int] | |
Foo = ref object | |
idRef: string | |
bar1Object: Option[Bar] | |
bar2Object: Option[Bar] | |
proc camel2snake*(s: string): string = | |
## CanBeFun => can_be_fun | |
## https://forum.nim-lang.org/t/1701 | |
result = newStringOfCap(s.len) | |
for i in 0..<len(s): | |
if s[i] in {'A'..'Z'}: | |
if i > 0: | |
result.add('_') | |
result.add(chr(ord(s[i]) + (ord('a') - ord('A')))) | |
else: | |
result.add(s[i]) | |
template dumpKey(s: var string, v: string) = | |
const v2 = v.camel2snake().toJson() & ":" | |
s.add v2 | |
proc dumpHook*(s: var string, v: object) = | |
s.add '{' | |
var i = 0 | |
when compiles(for k, e in v.pairs: discard): | |
# Tables and table like objects. | |
for k, e in v.pairs: | |
if i > 0: | |
s.add ',' | |
s.dumpHook(k) | |
s.add ':' | |
s.dumpHook(e) | |
inc i | |
else: | |
# Normal objects. | |
for k, e in v.fieldPairs: | |
when compiles(e.isSome): | |
if e.isSome: | |
if i > 0: | |
s.add ',' | |
s.dumpKey(k) | |
s.dumpHook(e) | |
inc i | |
else: | |
if i > 0: | |
s.add ',' | |
s.dumpKey(k) | |
s.dumpHook(e) | |
inc i | |
s.add '}' | |
var foo = Foo( | |
idRef: "0000-1234", | |
bar1Object: some(Bar(nameOfThing:"Bar", arr: @[1, 2, 3])) | |
) | |
echo foo.toJson() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment