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

出力:["aaa","bbb","ccc"]要素がJSON配列に存在するかどうかをチェックする方法は?

しかし、どのようにこの配列が要素を持っている場合、私は確認できますか? canFindをJSON配列で使用する方法を理解できません。私はvibed json moduleを使用しています。

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

することはできません:Got JSON of type array, expected string.

をした場合、次のように行うには:to!stringtoString方法では

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."

すべての作業:

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

if(test.toString.canFind("aaa")) 
{ 
    writeln("founded"); 
} 
0を私がしなければ

は、しかし、それは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

文字列[]の前後に中かっこを入れてみることはできますか? like .get! (文字列[])。canFind –

+0

私はコードを更新しました。配列を 'writeln'に渡している間にエラーが出る可能性はありますか?それは印刷の配列をサポートしていますか? –

+0

ええ、ごめんなさい。電話があったので、手に入れてください!(文字列[])は機能しません。 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

私はこの解決策をもっと好む。 can not find can findは述語を取ることができる! –

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"); 
} 
関連する問題