Torbjørn Torbjørn - 1 year ago 44
JSON Question

How to convert object to json in Nimrod

I'm making a small web service in Nimrod, and I need to respond to requests with json. I'm using the jester module to make the service. I expect I can use the json module in Nimrod's base library to construct some kind of object with fields and values, and then convert it to a json string. But how? Or is there a better way to construct json in Nimrod?

Answer Source

Ah, yes, the json module documentation only shows a brief example for parsing JSON but has no clear example on how to construct one. In Nim you create JsonNode objects which are object variants. These can be constructed with the individual procs like newJObject() and then populate the fields sequence. Another quicker way is to use the %() proc which accepts a sequence of tuples where one value is the string with the json field and the other the individual JsonNode.

Here's an example showing both ways:

import json

  Person = object ## Our generic person record.
    age: int ## The age of the person.
    name: string ## The name of the person.

proc `%`(p: Person): JsonNode =
  ## Quick wrapper around the generic JObject constructor.
  result = %[("age", %p.age), ("name",]

proc myCustomJson(p: Person): JsonNode =
  ## Custom method where we replicate manual construction.
  result = newJObject()
  # Initialize empty sequence with expected field tuples.
  var s: seq[tuple[key: string, val: JsonNode]] = @[]
  # Add the integer field tuple to the sequence of values.
  s.add(("age", newJInt(p.age)))
  # Add the string field tuple to the sequence of values.
  s.add(("name", newJString(
  result.fields = s

proc test() =
  # Tests making some jsons.
  var p: Person
  p.age = 24 = "Minah"
  echo(%p) # { "age": 24,  "name": "Minah"}
  p.age = 33 = "Sojin"
  echo(%p) # { "age": 33,  "name": "Sojin"}
  p.age = 40 = "Britney"
  echo p.myCustomJson # { "age": 40,  "name": "Britney"}

when isMainModule: test()