Parsing and managing json in Scala

I have this JSON that returns from the REST service that I use.

{ "id": "6804", "signatories": [ { "id": "12125", "fields": [ { "type": "standard", "name": "fstname", "value": "John" }, { "type": "standard", "name": "sndname", "value": "Doe" }, { "type": "standard", "name": "email", "value": " john.doe@somwhere.com " }, { "type": "standard", "name": "sigco", "value": "Company" } ] } ] } 

I'm currently exploring a way to parse this with json4s, iterating over the fields array to be able to change the value property of various objects. So far I have tried several json libs and ended up with json4s .

Json4s allows me to parse json in a JObject, which I can try to extract an array of "fields" from.

  import org.json4s._ import org.json4s.native.JsonMethods._ // parse to JObject val data = parse(json) // extract the fields into a map val fields = data \ "signatories" \ "fields" // parse back to JSON println(compact(render(fields))) 

I managed to extract such a Map and return it to JSON again. However, I canโ€™t understand how to lay these fields and change the โ€œvalueโ€ value in them?

I read the json4s documentation, but I'm very new to both Scala and syntax, so I have a hard time.

The question is, how do I iterate over the result of a JSON analysis to change the value of a property?

Here is the flow that I want to achieve.

  • Parsing JSON into an iterable object
  • Scroll and find the specific โ€œnamesโ€ and change their meaning, for example fstname, from John to another name.
  • Parse it back to JSON so that I can send a new JSON with updated values.

I donโ€™t know if this is really the best way to do this, I would really appreciate input, maybe there is an easier way to do this.

Thanks in advance, Best regards,

Stefan Conno

+6
source share
1 answer

You can convert json to an array of the case class, which is easiest to do. For example: you can have a case class for fields like

 case class Field(`type`: String, name: String, value: String) 

and you can convert your json to an array of fields, for example read[Array[Field]](json) where json is located

  [ { "type": "standard", "name": "fstname", "value": "John" }, ... ] 

which will give you an array of fields. Similarly, you can simulate your entire Json.

Since you now have an array of case classes, its a fairly simple iteration of objects and changing the value using the case copy method.

After that, to convert an array of objects to Json, you can simply use write(objects) (Json4s read and write functions are available in the org.json4s.native.Serialization package.

 Update 

To do this without converting it to a case class, you can use the transformField function

 parse(json).transformField{case JField(x, v) if x == "value" && v == JString("Company")=> JField("value1",JString("Company1"))} 
+6
source

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


All Articles