So I was wondering how can I actually use try to minimize me repeating a particular value and I could just refer to a different key present somewhere in the JSON.
For example in data.json
"loggingFile": "archive.txt"
...
...
"someKey": [
{
"name": "Gidrah",
"loggingFile": // Now refer back to top-level loggingFile
}
]
I have tried to search for it online and found here that there is something about references in JSOn and it could be used as if:
{
"schema": {
"$ref": "#/components/schemas/Pet"
}
}
But this does not work for me as nlohmann::json that I am using in C++ identifies it as an object rather than the string that I need to use.
Yes, JSONSchema files are preprocessed to replace references of the form {"$ref": ...}
. If you want something similar, you have to implement it yourself. You will need to do a recursive walk of the file and replace any references you see. nlohmann::json has support for JSON Pointer, which should suffice. Also take care to avoid introducing loops into your data structure.
Alternatively, consider switching to YAML where this feature is baked into the file format. &anchor
marks a node for reuse, and *anchor
inserts a reference to the original node.
loggingFile: &loggingFile archive.txt
someKey:
- name: Gidrah
loggingFile: *loggingFile