2016-10-11 15 views
0

特定のtargetFieldの文字列をスキャンし、そのフィールドの値を返すか(存在しない場合)nullのメソッドを実装する必要があります:GroovyでJSONフィールドの値を再帰的に抽出する

// Ex: extractFieldValue(/{ "fizz" : "buzz" }/, 'fizz') => 'buzz' 
// Ex: extractFieldValue(/{ "fizz" : "buzz" }/, 'foo') => null 
String extractFieldValue(String json, String targetField) { 
    // ... 
} 

この溶液を(階層)JSON文字列内の任意のネストレベルで再帰ワークなければなりません。また、JSON配列に対しても同様に動作する必要があります。

これまでの私の最高の試み:

String extractFieldValue(String json, String targetField) { 
    def slurper = new JsonSlurper() 
    def jsonMap = slurper.parseText(json) 

    jsonMap."${targetField}" 
} 

トップレベル(ネストされていない)JSONフィールド上のこの唯一の作品。私はGoogle GodsにJsonSlurperの使い方を尋ねましたが、役に立つものは何も見つかりませんでした。ここにどんなアイデア?

+1

何複数の一致か? –

+2

JSONをマップにスラップしたときは、http://stackoverflow.com/questions/6185746/groovy-map-find-recursiveのようなものを使用できます。 –

+0

良い点@tim_yates - 私は満足しています最初に見つかった値を取る。 – smeeb

答えて

2

jsonという変数で、この入力文字列を考える:

{ 
    "a":"a", 
    "b":{"f":"f", "g":"g"}, 
    "c":"c", 
    "d":"d", 
    "e":[{"h":"h"}, {"i":{"j":"j"}}], 
} 

このスクリプト:

import groovy.json.JsonSlurper 

def mapOrCollection (def it) { 
    it instanceof Map || it instanceof Collection 
} 

def findDeep(def tree, String key) { 
    switch (tree) { 
     case Map: return tree.findResult { k, v -> 
      mapOrCollection(v) 
       ? findDeep(v, key) 
       : k == key 
        ? v 
        : null 
     } 
     case Collection: return tree.findResult { e -> 
      mapOrCollection(e) 
       ? findDeep(e, key) 
       : null 
     } 
     default: return null 
    } 
} 

('a'..'k').each { key -> 
    def found = findDeep(new JsonSlurper().parseText(json), key) 
    println "${key}: ${found}" 
} 

は、これらの結果を与える:

a: a 
b: null 
c: c 
d: d 
e: null 
f: f 
g: g 
h: h 
i: null 
j: j 
k: null 
関連する問題