I am writing an api sever in Nim. The output is of the form:
{
code:"tk.01",
message: "Token in data field",
data:"12345"
}
data field could be a string, single object (say a blog post), or an array (sequence) of objects (list of posts). I was successful in emitting the string without any trouble. But I want to make a generic object that I can use to hold these values around the application.
type retVal = object
code: string
message: string
data: ?
I don't know what datatype data should be.
Also I am trying to create a proc that can output a json to the outside world (not just withing Nim application). Everything I tried with json module outputs as string rather than json (like the above) for objects.
The following code prints json correctly, but I'm lost how to pass json in and out of procs.
import marshal
type
Person = object
age: int
name: string
var p = Person(age: 38, name: "Torbjørn")
echo($$p)
Thanks
You can use JsonObject as a standin for any object.
import json
type
RetVal = object
code: string
message: string
data: JsonNode
const js1 = """
{
"code": "tk.01",
"message": "Token in data field",
"data": "string"
}
"""
const js2 = """
{
"code": "tk.01",
"message": "Token in data field",
"data": [1, 2, 3, 4]
}
"""
const js3 = """
{
"code": "tk.01",
"message": "Token in data field",
"data": {"key": "value"}
}
"""
proc main() =
let retVal1 = parseJson(js1).to(RetVal)
echo retVal1.data.to(string)
let retVal2 = parseJson(js2).to(RetVal)
echo retVal2.data.to(seq[int])
let retVal3 = parseJson(js3).to(RetVal)
for key, value in retVal3.data.pairs():
echo key, ": ", value.to(string)
main()
# Output:
#
# string
# @[1, 2, 3, 4]
# key: value