Is there a way to use circe-optics' JsonPath with strings, just as in jq CLI tool?
Asked Answered
H

0

6

What I'd like to do, is having field descriptor defined as field1.field2[1].field3, access value two of json:

{
  "field1": {
    "field2": [
      {
        "field3": "one"
      },
      {
        "field3": "two"
      }
    ]
  }
}

I know I can do that using applyDynamic and root.field1.field2.index(1).field3, but is there a way to create such a lens using a string?

Hephzipah answered 9/3, 2018 at 17:37 Comment(4)
applyDynamic accept StringCameo
Thank you @WeiChingLin for the pointer! - this is the correct answer. In fact, selectDynamic works a little nicer, eg. root.selectDynamic("some.path").string.getOption(jsonObj) (where you can switch out 'string' to be one of the other types in io.circe.optics.JsonPath, such as boolean or int, etc. The import you need is io.circe.optics.JsonPath._Translunar
root.selectDynamic("some.path") does not work. I do not see anything in JsonPath that would allow you to do such a query. Instead "some.path".split(".").foldLeft(root)((p,f) => p.selectDynamic(f)).string.getOption(jsonObject) works. Or without optics: "some.path".split(".").foldLeft[ACursor](json.hcursor)((p,f) => p.downField(f)).as[String].toOptionAleida
"some.path".split(".") should be "some.path".split("\\.") or "some.path".split('.')Aleida

© 2022 - 2024 — McMap. All rights reserved.