Search code examples
dvibed

How to Iterate through a JSON Array in Vibe.D?


What's the correct way, using the Vibe.D library, to iterate through a Json array?

I have tried this, but it gives me compile errors:

foreach(string index, Json value; configuration["array1"]) {}

This is the error:

Error: opApply() function for Json must return an int

Full code:

foreach(int index, Json pluginToLoad; configuration["PluginsToLoad"]) {
    import std.conv;
    logInfo(to!string(index));
    logInfo(pluginToLoad.get!string);
    logInfo("---");
}

Solution

  • In your code index must be of integer type - this is pretty much what error message says. JSON array is always plain array, associative ones are called JSON objects.

    Example:

    foreach (size_t index, Json value; configuration["array1"]) {}
    

    or simply

    foreach (index, value; configuration["array1"]) {} // type inference
    

    Update: changed int to size_t to match actual opApply signature