Nim: How to parse JSON
Mar 21, 2022
To parse a JSON string into an object, use the json
import from the standard library:
import jsonlet jsonObject = """{"first_name": "glenn", "last_name": "gillen"}"""let jsonArray = """[7, 8, 9]"""let parsedObject = parseJson(jsonObject)let parsedArray = parseJson(jsonArray)
This will create a series of nodes, on which you'll need to call getStr()
, getInt()
, getFloat()
, or getBool()
to retrieve the actual value:
ech parsedObject["first_name"].getStr() # glennecho parsedArray[1].getInt() # 8
If you've a nested JSON object Nim will automatically parse the nesting and you'll only need to call the get*()
on the edge node:
import jsonlet jsonObject = """{"names": {"first": "glenn","last": "gillen"}}"""let parsedObject = parseJson(jsonObject)echo parsedObject["names"]["first"].getStr() # glenn
To parse into an object, you'll need to define an object that matches your expected structure:
import jsontypePerson = objectfirst_name: stringlast_name: stringlet jsonObject = parseJson("""{"first_name": "glenn", "last_name": "gillen"}""")let person = to(jsonObject, Person)echo person.first_name # glenn
Hi, I'm Glenn! 👋 I've spent most of my career working with or at startups. I'm currently the Director of Product @ Ockam where I'm helping developers build applications and systems that are secure-by-design. It's time we started securely connecting apps, not networks.
Previously I led the Terraform product team @ HashiCorp, where we launched Terraform Cloud and set the stage for a successful IPO. Prior to that I was part of the Startup Team @ AWS, and earlier still an early employee @ Heroku. I've also invested in a couple of dozen early stage startups.
Previously I led the Terraform product team @ HashiCorp, where we launched Terraform Cloud and set the stage for a successful IPO. Prior to that I was part of the Startup Team @ AWS, and earlier still an early employee @ Heroku. I've also invested in a couple of dozen early stage startups.