Hi,
i am struggling with the json module. Currently i am trying to map a json from file to an object. Here is the code:
import json
type Config = object
rootDev: string
grubDevLabel: string
title: string
updateGrubDir: string
proc readConfig(): Config =
result = parseFile("grubify.json")
when isMainModule:
var config: Config = readConfig()
echo(config.rootDev)
the error message is
parseJsonFile.nim(10, 23) Error: type mismatch: got (JsonNode) but expected 'Config'
What is JsonNode. I read the documentation of the json module but I got not englighted enough to understand how to work with a jsonNode...
Thanks for your help.
Hi,
JsonNode is return type of parseFile function.
You must assign each field of JsonNode to its corresponding field in your Config object.
Look at the example at the start of json documentation:
proc readConfig(): Config =
var js: JsonNode
js = parseFile("grubify.json")
result.rootDev = js["rootDev"].str
result.grubDevLabel = js["grubDevLabel"].str
result.title = js["title"].str
result.updateGrubDir = js["updateGrubDir"].str
the documentation lacks on some edges with examples. But the git repos of Dom96 and def- are great. The most parts I have learned so far are from their repos. I read in the github issues tracker that there is an issue of adding more examples, but I have no idea whether my help is useful, because I have much more to learn how nim works.
proc readConfig(): Config =
let js = parseFile("grubify.json")
result.rootDev = js["rootDev"].str
result.grubDevLabel = js["grubDevLabel"].str
result.title = js["title"].str
result.updateGrubDir = js["updateGrubDir"].str
Since YAML is a superset of JSON, you can use NimYAML to deserialize the JSON file. It is able to automatically map a JSON object to a Nim object:
import yaml.serialization, streams
type Config = object
rootDev: string
grubDevLabel: string
title: string
updateGrubDir: string
proc readConfig(): Config =
var s = newStringStream("""
{
"rootDev": "rootDevValue",
"grubDevLabel": "gdlValue",
"title": "titleValue",
"updateGrubDir": "ugdValue"
}
""")
load(s, result)
let config = readConfig()
To load a file, simply use a FileStream instead of a StringStream. Note that the names of the object's fields must match exactly.