I have an Array in scala which looks like:
Input = [(KeyID, Field_1, Field_2, { 'id': 1, 'name': 'John'},{ 'id': 2, 'name': 'Dani'})]
Essentially, I want to extract the fields: Field_1, Field_2 and the JSON as a field itself:
Field_1, Field_2, { 'id': 1, 'name': 'John'},{ 'id': 2, 'name': 'Dani'}
I tried to delete the () at the very end and beginning by using:
Input.replaceAll("[()]","")
However, sometimes the json also contains parentheses, how to extract the fields independently and how to preserve the json structure?
By trying to split the string, I'm getting:
Field_1, Field_2, id, 1, name, John, id, 2, name, Dani
CodePudding user response:
I'm not sure this is actually answering the question, but I hope this helps.
Assume you have this data:
val Input = Array((KeyID, Field_1, Field_2, "{ 'id': 1, 'name': 'John'}", "{ 'id': 2, 'name': 'Dani'}"))
Array
is a Java type so the first thing to do is to convert to a Scala List
. Then you can extract the fields using a simple map
.
val input = Input.toList
val keys = input.map(_._1)
val field1 = input.map(_._2)
val field2 = input.map(_._3)
val json1 = input.map(_._4)
val json2 = input.map(_._5)
Each val
will contain a List
of the particular field.
If you want to process the JSON itself there are various Scala libraries out there to do it. Pick one and then come back if you have specific problems getting it to work.