2

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("---");
}
Jeroen
  • 15,257
  • 12
  • 59
  • 102
  • 1
    looks like the vibe.d guys didn't implement opApply - I'd file this as a bug with them. I don't know the right way to do it though, I'm not a vibed user :( – Adam D. Ruppe Feb 19 '14 at 16:39
  • Can you show a full example? As I think your code should work. This page has an example using foreach on a `Json` object. http://vibed.org/api/vibe.data.json/ – yaz Feb 19 '14 at 19:34
  • @yaz That's what my code is based of basically. `configuration` is an object of type Json. I don't have access to my code atm but I'll give it as soon as possible. (Different computer) – Jeroen Feb 19 '14 at 19:38

2 Answers2

3

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

Mihails Strasuns
  • 3,783
  • 1
  • 18
  • 21
  • I tried that but it won't allow me to set the value to string in that case. – Jeroen Feb 19 '14 at 21:50
  • `Error: cannot uniquely infer foreach argument types` – Jeroen Feb 20 '14 at 20:09
  • Does this mean `opApply` isn't implemented properly? I've Googled the problem and `opApply` seems to be a popular problem. Adam D. Ruppe also suggested something similar. – Jeroen Feb 20 '14 at 20:19
  • 1
    I have had a look at JSON source code and probably inference does not work simply because there are too many opApply overloads (http://vibed.org/api/vibe.data.json/Json.opApply) , so compiler can't guess one to use. – Mihails Strasuns Feb 20 '14 at 21:17
0

For some reason, using a ulong works. I'm guessing this is a bug?

foreach(ulong index, Json pluginToLoad; configuration["PluginsToLoad"])
Jeroen
  • 15,257
  • 12
  • 59
  • 102