Access and modify part of an arbitrary Json object

70 views
Skip to first unread message

Tim Fry

unread,
Sep 23, 2015, 4:03:45 AM9/23/15
to argonaut-json
Given this Json: 

    { "name" : "joe", "age": 21, "arbitraryJson": { "field1": "value1", "field2":"value2"} }

where the content of "arbitraryJson" can be any valid Json (i.e., this part of the schema is unknown),  I'd like to encode and decode it into class like this:

case class Person (name: String, age: Int, arbitraryJson: String )

with the arbitraryJson Base64-encoded/decoded. 

Is this possible with Argonaut? I've played around with various decoding and parsing tests, lenses and examples, but couldn't find anything that seemed to do something similar. I need to treat the entire Json tree below arbitrary Json as just a string, but it's not obvious how to do this.

Anyone have any examples of such a thing?

Thanks

Tim

(pardon me for cross-posting this to Argonaut/Issues in Github)

Ionuț G. Stan

unread,
Sep 23, 2015, 6:55:51 AM9/23/15
to argona...@googlegroups.com
How about storing the arbitrary JSON part as an Argonaut Json data type.
Is that within your constraints?

scala> import argonaut._, Argonaut._
import argonaut._
import Argonaut._

scala> val payload = """ { "name" : "joe", "age": 21, "arbitraryJson": {
"field1": "value1", "field2":"value2"} } """
payload: String = " { "name" : "joe", "age": 21, "arbitraryJson": {
"field1": "value1", "field2":"value2"} } "

scala> case class Person(name: String, age: Int, arbitraryJson: Json)
defined class Person

scala> implicit val jsonCodec: CodecJson[Person] =
casecodec3(Person.apply, Person.unapply)("name", "age", "arbitraryJson")
jsonCodec: argonaut.CodecJson[Person] = argonaut.CodecJson$$anon$1@2eabe6d3

scala> payload.decodeOption[Person]
res0: Option[Person] =
Some(Person(joe,21,{"field1":"value1","field2":"value2"}))
> --
> You received this message because you are subscribed to the Google
> Groups "argonaut-json" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to argonaut-jso...@googlegroups.com
> <mailto:argonaut-jso...@googlegroups.com>.
> For more options, visit https://groups.google.com/d/optout.


--
Ionuț G. Stan | http://igstan.ro
Reply all
Reply to author
Forward
0 new messages