Search code examples
jsondvibed

Iterate JSON during compile-time, in Dlang


I want to iterate over the JSON using CTFE. I have tried both std.json and vibe.data.json, but there is no luck. I am not sure what I am missing.

import std.stdio;
import std.json;
import std.array;
import vibe.data.json;

void main()
{
    enum string config = `{ "ModelNames": [ "Bank", "Biller", "Aggregator" ] }`;
    const auto c1 = parseJSON(config);
    immutable auto c2 = parseJsonString(config);
    
    foreach (key; c1["ModelNames"].array)
        writeln(key.get!string);

    foreach (key; c2["ModelNames"])
        writeln(key.get!string);

    // static foreach (key; c1["ModelNames"].array)
    //  pragma(msg, key.get!string);

    // static foreach (key; c2["ModelNames"])
    //  pragma(msg, key.get!string);
}

Solution

  • Wrap your logic into a regular D function, then get the compiler to evaluate it at compile-time by calling it is a context where the result must be known at compile-time, such as using the result in an enum:

    import std.algorithm.iteration;
    import std.stdio;
    import std.json;
    import std.array;
    
    void main()
    {
        enum string config = `{ "ModelNames": [ "Bank", "Biller", "Aggregator" ] }`;
    
        static string[] getModelNames(string json)
        {
            auto c1 = parseJSON(json);
            return c1["ModelNames"].array.map!(item => item.str).array;
        }
    
        enum string[] modelNames = getModelNames(config);
        pragma(msg, modelNames);
    }