How to deeply move a Groovy object with a dot in a row using GPath

The situation that I have is that I am querying MongoDB with a string for a field with more than one level in the hierarchy of objects. This query should be a string. So, for example, I request something like this in Groovy:

def queryField = 'abc' //this is variable and can be different every time def result = mongodb.collection.findOne([queryField:5]) 

The problem does not arise that as a result I want to find the value of the nested field. With GPath, I could go one level and get the value

 def aObj = result."a" //or result["a"] 

However, I want to delve into this by doing something like this:

 def queryField = "abc" //this can change every time and is not always 'abc' def cObj = result[queryField] //since field is variable, can't just assume result.abc 

This is not working in Groovy right now. There is an error recorded here , but I was wondering if there is a more efficient work for this scenario, which is a little cleaner than my parsing string, breaking into a point, and then building a traversal of the object. Note that "abc" is variable and unknown at run time (for example, it may be "abd").

+4
source share
1 answer

Based on the error / thread, there may have been some ambiguity issues related to supporting access to point access objects. Based on the mailing list thread, it seems that queryField string evaluation would be your best bet:

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

Script on Groovy Web Console

The mailing list sheet is a bit outdated, so there is a new-ish (at least 1.7.2) Eval class that can help with running small snippets that don't have much binding.

Otherwise, you can split the string and recursively evaluate the properties of the object, effectively reproducing a subset of the GPath traversal behavior.

+2
source

Source: https://habr.com/ru/post/1395267/


All Articles