1

I am using "com.jayway.jsonpath" % "json-path" % "2.7.0" for parsing an incoming json message in our API build on akka-http written in scala. The incoming message can have array of records and for each record, some actions will be performed. While trying to access each record from that array, colon(:) is being converted to equals to(=). Below is the code:

val conf= com.jayway.jsonpath.Configuration.defaultConfiguration.addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL)
val doc = JsonPath.using(conf).parse(input)
val arrLen = doc.read("$.records.length()").toString.toInt
              for(i <- 0 until( arrLen)){
                val str = "$.records["+i+"]"
                val rec = doc.read(str).toString
                println(rec)
              }

The payload which I am trying to parse:

{"schema_id":"1","records":[{"application":{"applicationRevision":{"string":"27904"},"applicationVersion":"india","id":"132231","name":"appTest"},"guest":{"session":"12bvg","systemTime":"2021-08-24T21:19:13.282Z","visitorId":"abc"}}]}

This is what I am getting after accessing element from the records array:

{application={applicationRevision={string=27904}, applicationVersion=india, id=132231, name=appTest}, guest={session=12bvg, systemTime=2021-08-24T21:19:13.282Z, visitorId=abc}}

All the colons(:) have been converted into equals(=). How can we prevent this to happen so that the payload remain intact without colon to equals conversion?

Gaël J
  • 11,274
  • 4
  • 17
  • 32
sam.ban
  • 238
  • 3
  • 13
  • The `=` is just the way `toString` prints it. What's the type of `doc.read(str)`? I guess it's a Map or something similar. – Gaël J Dec 29 '22 at 10:07
  • The type is scala Nothing. That's why I am converting it to String.. – sam.ban Dec 29 '22 at 10:11
  • It's not `Nothing`, otherwise you couldn't get such string output. Use `.getClass` for instance and you'll know. Anyway it seems the proper way to use this API is to give it the expected return type, I recommend looking more at the doc of the API. If you want to work with it, you'll need it. – Gaël J Dec 29 '22 at 10:59
  • If I may, you can also consider other "more standard" Scala libraries to parse JSON: play-json, Circe, zio-json, Jackson... – Gaël J Dec 29 '22 at 11:00
  • 1
    Thanks.. Yeah it is returning java.util.LinkedHashMap.. Basically, our codebase was build on JsonPath. But definitely, I can use play-json to achieve this piece.. – sam.ban Dec 29 '22 at 12:38
  • Okay, then the `=` are definitely the string representation of Map. – Gaël J Dec 29 '22 at 12:54

1 Answers1

0

It is pretty easy using play, just a single line solution:

(Json.parse(input) \ "records").as[List[JsValue]].map(ele => ele.toString()).map{rec =>
            //business logic
          }

Add play in your build.sbt(in my case) like this:

"com.typesafe.play" %% "play" % "2.8.16"
sam.ban
  • 238
  • 3
  • 13