Way to deep traverse a Groovy object with dot in string using GPath

后端 未结 1 1082
傲寒
傲寒 2021-01-13 14:32

The situation I have is that I\'m querying MongoDB with a string for a field that is more than one level deep in the object hierarchy. This query must be a string. So for

1条回答
  •  不知归路
    2021-01-13 15:07

    Based on the bug/thread it would appear there are some ambiguity problems with supporting a dotted property accessor. Based on the mailing list thread it would seem that evaluating the queryField string would be your best bet:

    def result = [a: [b: [c: 42]]]
    def queryString = 'a.b.c'
    
    def evalResult = Eval.x(result, 'x.' + queryString)
    assert evalResult == 42
    

    Script on Groovy Web Console

    The mailing list thread is a little old, so there's a new-ish (since at least 1.7.2) Eval class that can help out with running small snippets that don't have a large binding.

    Otherwise, you can split the string and recursively do property evaluations on the object, effectively reproducing a subset of GPath traversal behavior.

    0 讨论(0)
提交回复
热议问题