简体   繁体   中英

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);
}

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);
}

Thanks to Vladimir, the trick he specifies work perfectly both for std.json and vibe.data.json.

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

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

    static foreach (key; c2["ModelNames"].array.map!(item => item).array)
        pragma(msg, key.get!string);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM