klaxon icon indicating copy to clipboard operation
klaxon copied to clipboard

Finding a nested object when we don't know the full path

Open oripwk opened this issue 6 years ago • 1 comments

How can we return a nested object?

Let's say I have

{ "a": { "b": { "c": 1 } } }

How do I retrieve "c"?

JsonBase.lookup(…) receives only full paths so if I don't know the full path to "c" I cannot use this.

On the other hand, PathMatcher cannot return anything since it has a method onMatch(…) that happens in the background and you cannot return anything from this method.

oripwk avatar Dec 02 '18 17:12 oripwk

Indeed the lack of a return value when using path matcher is confusing. Naively users may expect it to behave similarly to FileFilter from java sdk to match and filter the parsed DOM, but it does not do so. In fact the return value of

val parsed = Klaxon().pathMatcher(object : PathMatcher {
                    override fun pathMatches(path: String) = Pattern.matches(".*Snapshots.*SnapshotRaw.Containers.*", path)
                    override fun onMatch(path: String, value: Any) {
                        println(value)}
                }).parseJsonObject(StringReader(endPointsJson!!))

seems to be always the same no matter what path is used.

What for sure works is (((parsed["Snapshots"] as JsonArray<*>)[0] as JsonObject)["SnapshotRaw"] as JsonObject)["Containers"] but this lacks beauty so some path like query would be really helpful here.

Also parsed.array<Any>("Snapshots[0].SnapshotRaw.Containers") does not seem be applicable here.

holgerbrandl avatar May 21 '20 07:05 holgerbrandl