Hello everyone!
I am trying to deserialize a JSON object but so far I have been unable to do so. Here is my toy module:
import json
when isMainModule:
let jsonObject = parseJson("""
{
"archived_snapshots": {
"closest": {
"available": true,
"url": "http://web.archive.org/web/20130919044612/http://example.com/",
"timestamp": "20130919044612",
"status": "200"
}
}
}
""")
type
ArchivedSnapshot = object of RootObj
closest: Closest
Closest = object of ArchivedSnapshot
available: bool
url: string
timestamp: string
status: string
let snapshot = to(jsonObject, ArchivedSnapshot)
echo(snapshot.available)
echo(snapshot.url)
echo(snapshot.timestamp)
echo(snapshot.status)
I get:
Error: undeclared field: 'available' for type jsonParser.ArchivedSnapshot
I don't have much experience with nim so i appreciate any help.
Best regards.
You have to account for the root object which is above "archived_snaphots". Moreover your type ArchivedSnapshot doesn't have direct access to the fields available, url because they belong to type closest. I'm surprised the code above compiles - you are declaring Closest to be of type ArchivedSnapshot which has a Closest type which is of type ArchivedSnapshot. I'd expect the compiler to complain or have some problems with code generation.
This is probably what you wanted:
import std/json
when isMainModule:
type UrlStatus = object
available: bool
url: string
timestamp: string
status: string
type Snapshot = object
closest: UrlStatus
type Data = object
archivedSnapshot: Snapshot
let jsonObject = parseJson("""
{
"archivedSnapshot": {
"closest": {
"available": true,
"url": "http://web.archive.org/web/20130919044612/http://example.com/",
"timestamp": "20130919044612",
"status": "200"
}
}
}
""")
let root = to(jsonObject, Data)
echo(root.archivedSnapshot.closest.available)
echo(root.archivedSnapshot.closest.url)
echo(root.archivedSnapshot.closest.timestamp)
echo(root.archivedSnapshot.closest.status)
Thanks a lot! It worked as expected.
Best regards.