parsetoml
parsetoml copied to clipboard
`TomlValueRef.to(object)`
That's a feature I'm really missing with using parsetoml.
I'm aware that I could use toJson
but this doesn't feels natural:
import json, parsetoml
parsetoml.parseFile("mycfg.toml").toJson().to(object)
For those like me trying the suggested code above, it doesn't work. This is because parsetoml
doesn't generate JSON for serialization but for testing. So the object (srcDir: "docsrc", "homeDir": "docs")
is generated as: {"srcDir":{"type":"string","value":"docsrc"},"homeDir":{"type":"string","value":"docs"}}
. I solved this by modifying their toJson
proc to output the expected JSON instead:
proc customToJson*(table: parsetoml.TomlTableRef): JsonNode
proc customToJson*(value: parsetoml.TomlValueRef): JsonNode =
case value.kind:
of TomlValueKind.Int:
%* value.intVal
of TomlValueKind.Float:
if classify(value.floatVal) == fcNan:
if value.forcedSign != Pos:
%* value.floatVal
else:
%* value.floatVal
else:
%* value.floatVal
of TomlValueKind.Bool:
%* $value.boolVal
of TomlValueKind.Datetime:
if value.dateTimeVal.shift == false:
%* value.dateTimeVal
else:
%* value.dateTimeVal
of TomlValueKind.Date:
%* value.dateVal
of TomlValueKind.Time:
%* value.timeVal
of TomlValueKind.String:
%* value.stringVal
of TomlValueKind.Array:
if value.arrayVal.len == 0:
when defined(newtestsuite):
%[]
else:
%* []
elif value.arrayVal[0].kind == TomlValueKind.Table:
%value.arrayVal.map(customToJson)
else:
when defined(newtestsuite):
%*value.arrayVal.map(customToJson)
else:
%* value.arrayVal.map(customToJson)
of TomlValueKind.Table:
value.tableVal.customToJson()
of TomlValueKind.None:
%*{"type": "ERROR"}
proc customToJson*(table: parsetoml.TomlTableRef): JsonNode =
result = newJObject()
for key, value in pairs(table):
result[key] = value.customToJson
I haven't tested it extensively but I hope someone can have some use for it until direct deserialization support is added to parsetoml
:)
Yes the JSON output of parsetoml is for testing through the burntsushi TOML conformance test. Having a native to
would be nice.