I'm trying to create a json object that is exported and available to other Javascript libraries. Here's a trivial example below. The code below works, I can generate the js file, access the exported vars in the browser js console and it works with my other library.
But I wish it weren't so verbose. My real json objects will be much larger, more deeply nested and have many more variations in format. I really like the %* macro in the json module, but the js it generates is not in a format that other libraries can use.
How can this be improved?
import jsffi
# {
# "friends": [
# {
# "val": 19,
# "name": "wendy",
# "lang": "nim"
# }
# ],
# "name": "sam",
# "val": 21
# }
proc makeObj1(): JsObject =
result = newJsObject()
result.val = 19
result.name = cstring"wendy"
result.lang = cstring"nim"
proc makeObj2(): JsObject =
result = newJsObject()
result.friends = [
makeObj1()
]
result.name = cstring"sam"
result.val = 21
var myobj2 {.exportc: "myobj2".} = makeObj2()
Compile with -d:danger and put name on everything relevant with {.exportc.}.
Your code will probably go thru a Minifier anyways, so maybe better focus on tests and documentation.
Some more research turned up a macro in jsffi that works the way I want. Here's the improved code.
import jsffi
type
Person = ref object of JsObject
name: cstring
val: int
lang: cstring
Rec = ref object of JsObject
name: cstring
val: int
let obj1 {.exportc: "obj1".} = Rec{
friends: [
Person{
val: 19,
name: "wendy",
lang: "nim"
}
],
name: "sam",
val: 21
}
var myobj1 {.exportc: "myobj1".} = obj1