【问题标题】:How to Iterate through a JSON Array in Vibe.D?如何在 Vibe.D 中遍历 JSON 数组?
【发布时间】:2014-02-19 13:09:33
【问题描述】:

使用 Vibe.D 库迭代 Json 数组的正确方法是什么?

我试过这个,但它给了我编译错误:

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

这是错误:

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

完整代码:

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

【问题讨论】:

  • 看起来 vibe.d 的家伙没有实现 opApply - 我会将此作为错误提交给他们。不过我不知道正确的方法,我不是一个有活力的用户:(
  • 你能展示一个完整的例子吗?因为我认为您的代码应该可以工作。此页面有一个在 Json 对象上使用 foreach 的示例。 vibed.org/api/vibe.data.json
  • @yaz 这就是我的代码的基础。 configuration 是 Json 类型的对象。我无权访问我的代码 atm,但我会尽快提供。 (不同的电脑)

标签: d vibed


【解决方案1】:

在您的代码中,index 必须是整数类型 - 这几乎就是错误消息所说的内容。 JSON 数组总是普通数组,关联的称为 JSON 对象。

例子:

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

或者干脆

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

更新:将 int 更改为 size_t 以匹配实际的 opApply 签名

【讨论】:

  • 我试过了,但在这种情况下它不允许我将值设置为字符串。
  • Error: cannot uniquely infer foreach argument types
  • 这是否意味着opApply 没有正确实现?我用谷歌搜索了这个问题,opApply 似乎是一个流行的问题。 Adam D. Ruppe 也提出了类似的建议。
【解决方案2】:

由于某种原因,使用 ulong 有效。我猜这是一个错误?

foreach(ulong index, Json pluginToLoad; configuration["PluginsToLoad"])

【讨论】:

  • 不,它匹配 JSON 模块中的 opApply 签名(签名和未签名不是可以互换的 afaik)
猜你喜欢
  • 2018-10-05
  • 2014-01-13
  • 2021-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-05
  • 1970-01-01
相关资源
最近更新 更多