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?
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()