如何检查 JSON 数组中是否存在元素?

How to check if element exists in JSON array?

Json test = Json.emptyArray;
test ~= "aaa";
test ~= "bbb";
test ~= "ccc";
writeln(test);

输出:["aaa","bbb","ccc"]

但是我如何检查这个数组是否有元素?我不知道如何将 canFind 与 JSON 数组一起使用。我正在使用 vibed json module.

if(test.get!string[].canFind("aaa"))
{
    writeln("founded");
}

无效:Got JSON of type array, expected string.

如果这样做:

if(test.get!(string[]).canFind("aaa"))
{
    writeln("founded");
}

Error: static assert "Unsupported JSON type 'string[]'. Only bool, long, std.bigint.BigInt, double, string, Json[] and Json[string] are allowed."

使用 to!stringtoString 方法都有效:

Json test = Json.emptyArray;
test ~= "aaa";
test ~= "bbb";
test ~= "ccc";
writeln(to!string(test));

if(test.toString.canFind("aaa"))
{
    writeln("founded");
}

但是如果我这样做是在 foreach 里面:

foreach(Json v;visitorsInfo["result"])
{
if((v["passedtests"].toString).canFind("aaa"))
 {
    writeln("founded");
 }
}

我得到:Error: v must be an array or pointer type, not Json。怎么了?

这有效 - 虽然不是特别好。

void main(){

    Json test = Json.emptyArray;

    test ~= "foo";
    test ~= "bar";
    test ~= "baz";

    foreach(ele; test){
        if(ele.get!string == "foo") {
            writeln("Found 'foo'");
            break;
        }
    }
}

可以像这样把它放在辅助函数中:

bool canFind(T)(Json j, T t){
  assert(j.type == Json.Type.array, "Expecting json array, not: " ~ j.type.to!string);

  foreach(ele; j){
    // Could put some extra checks here, to ensure ele is same type as T.
    // If it is the same type, do the compare. If not either continue to next ele or die
    // For the purpose of this example, I didn't bother :)

    if(ele.get!T == t){
       return true;
    }
  }
  return false;
}

// To use it
if(test.canFind("foo")){
  writefln("Found it");
}

JSON 数组对象是其他 JSON 元素的数组。它们不是字符串数组,这就是 elem.get!(string[]) 在编译时失败的原因。

将 JSON 元素切片以获得子元素数组,然后使用 canFind 的谓词参数从每个子元素中获取一个字符串。

writeln(test[].canFind!((a,b) => a.get!string == b)("foo"));