2016-05-13 99 views
0
Json test = Json.emptyArray; 
test ~= "aaa"; 
test ~= "bbb"; 
test ~= "ccc"; 
writeln(test); 

输出:["aaa","bbb","ccc"]如何检查JSON数组中是否存在元素?

但如何我可以检查这个数组有元素?我无法弄清楚如何在JSON数组中使用canFind。我正在使用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。怎么了?

+1

你可以尝试把括号括在你的字符串[]?像.get! (string [])。canFind –

+0

我更新了代码。将数组传递给'writeln'可能会导致错误吗?它支持打印数组吗? –

+0

对,对不起。在电话中,所以get!(string [])将不起作用。它必须转换为以下类型之一:http://vibed.org/api/vibe.data.json/Json.get –

回答

5

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

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

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

我更喜欢这个解决方案。甚至没有意识到canFind可以预测! –

0

这可行 - 虽然不是特别好。

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