How to evaluate a JSON file at compile time and create a struct out of it?
Ferhat Kurtulmuş
aferust at gmail.com
Fri Oct 4 10:27:27 UTC 2024
On Friday, 4 October 2024 at 08:45:49 UTC, holyzantaclara wrote:
> Hello hello everyone ^_^,
>
> I am new in D, and started this morning. I found a way to read
> a file at compile time with `-J.` and `static string content =
> import("my_json_file.json")`
>
> But then tried to statically evaluate with `static JSONValue j
> = parseJson(content)` but it fails.
>
> ```sh
> main.d(12): Error: variable `content` cannot be read at compile
> time
> main.d(12): called from here: `readJSON(content)`
> ```
>
> Is there a way to achieve this?
>
> My goal is to have a JSONValue at runtime that would be already
> present in the binary. Cause the JSONValue is huge. Like
> megabytes of data... And no I don't want to deal with a
> database for now.
>
> Thank you !
If you use dub, have a "stringImportPaths" field in dub.json
which works for me.
dub.json:
```
{
"name": "foo",
"stringImportPaths": [
"./"
]
}
```
my_json_file.json:
```
{
"name": "foo"
}
```
```
import std;
void main(){
immutable content = import("my_json_file.json");
pragma(msg, content);
immutable mjson = parseJSON(content);
writeln(mjson);
}
```
```
yields:
```
{
"name": "foo"
}
Linking foo
Running foo.exe
{"name":"foo"}
```
More information about the Digitalmars-d-learn
mailing list