Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to parse a JSON file in Nim using the standard library?

I’m learning Nim and trying to parse a JSON file. My JSON looks like this:

{
  "name": "John Doe",
  "age": 30,
  "skills": ["Nim", "Python", "C++"]
}

I found some examples in the Nim docs about JSON manipulation, but I’m still a bit confused about how to properly read and parse the file into a usable data structure.

Could someone show an example of how to properly access nested data or convert it into a Nim object?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any help or example code would be greatly appreciated!

>Solution :

You can use Nim’s json module to parse JSON and access fields using the bracket notation. The returned type from parseJson is a JsonNode, which provides various functions like getStr(), getInt(), and so on. Here’s a minimal example that illustrates how to read your file, parse the JSON, and access the fields:

import json, os


let fileContent = readFile("data.json")
let parsedJson  = parseJson(fileContent)


let nameField = parsedJson["name"].getStr()
echo "Name: ", nameField


let ageField = parsedJson["age"].getInt()
echo "Age: ", ageField

let skillsField = parsedJson["skills"]
for skill in skillsField:
  echo "Skill: ", skill.getStr()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading