I need to add a field to each element of multiple nested json array. For example I need to turn this (adding “Name” : “John Doe” field to each element of People):
{
"A" : {
"Hair" : "Black",
"Eyes" : "Blue",
"People" : [
{
"RSVP": "Yes"
},
{
"RSVP": "Yes"
},
{
"RSVP": "Yes"
}
]
},
"B" : {
"People" : [
{
"RSVP": "Yes"
}
]
},
"C" : {
"D" : {
"E" : [
{
// people does not exist here purposefully
}
]
}
},
}
into this exactly:
{
"A" : {
"Hair" : "Black",
"Eyes" : "Blue",
"People" : [
{
"RSVP": "Yes",
"Name": "John Doe"
},
{
"RSVP": "Yes",
"Name": "John Doe"
},
{
"RSVP": "Yes",
"Name": "John Doe"
}
]
},
"B" : {
"People" : [
{
"RSVP": "Yes",
"Name": "John Doe"
}
]
},
"C" : {
"D" : {
"E" : [
{
// people does not exist here purposefully
}
]
}
},
}
so far in my code, I have this:
// body param would be the original Json document in the above example
private def makeJson(body: Json): List[Json] = {
val pplList: List[String] = List(
"A.People",
"B.People",
"C.D.E.People"
)
val c = pplList.foldLeft(List.empty[Json])((acc, p) => {
// Split list into segments
val pSegments = p.split('.').toList
// check if each people path exists
val cursor = pSegments.foldLeft(body.hcursor.withFocus(root => root))((acc, segment) => acc.downField(segment))
if (cursor.succeeded) {
// if it exists, for every person in people array, add a field "Name" : "John Doe" to it
val people = cursor.as[List[Json]].getOrElse(List.empty).map(addName)
acc :+ people.asJson
} else {
acc
}
})
c
}
// leave person parameter here, I will need it later
private def addName(person: Json): Json = {
Json.obj("Value" -> Json.fromString("John Doe"))
}
I am able to dynamically construct the new json to insert with what I have now which is:
List([
{
"RSVP": "Yes",
"Name": "John Doe"
},
{
"RSVP": "Yes",
"Name": "John Doe"
},
{
"RSVP": "Yes",
"Name": "John Doe"
}
], [
{
"RSVP": "Yes",
"Name": "John Doe"
}
])
but I can’t find a good way to get it to my desire end result (insert it into the original json). Any ideas? Thank you!