Reputation: 146
I want to convert all the JSON key values the Map. Where I need key as gpath result and value as object key value.
Input Json
{
"employees": {
"employee": [{
"id": "1",
"firstName": "Tom",
"lastName": "Cruise",
"photo": "https://pbs.twimg.com/profile_images/735509975649378305/B81JwLT7.jpg"
},
{
"id": "2",
"firstName": "Maria",
"lastName": "Sharapova",
"photo": "https://pbs.twimg.com/profile_images/3424509849/bfa1b9121afc39d1dcdb53cfc423bf12.jpeg"
},
{
"id": "3",
"firstName": "James",
"lastName": "Bond",
"photo": "https://pbs.twimg.com/profile_images/664886718559076352/M00cOLrh.jpg"
}
]
}
}
Output I am expecting,
[employees.employee[0].id:"1",
employees.employee[0].firstName:"tom",
....]
I have tried Groovy jsonSurper() object class but I am unable to find solution to map all keys into gpath.
Any help will be appreciated!
Upvotes: 0
Views: 435
Reputation: 171104
Bit of an odd request... Can't think of why you'd want to do it... but anyway, you'd need to write some logic to recurse through the map generated by JsonSlurper, and collapse the keys...
Assuming your above json is in a String variable json
:
def map = new JsonSlurper().parseText(json)
def collapseKey(String prefix, Map result, value) {
if (value instanceof Map) {
value.each { k, v ->
collapseKey("${prefix ? "${prefix}." : ''}$k", result, v)
}
} else if (value instanceof List) {
value.eachWithIndex{ e, idx ->
collapseKey("${prefix}[$idx]", result, e)
}
} else {
result."$prefix" = value
}
result
}
def result = collapseKey("", [:], map)
You could (of course) just parse it into a map and do:
map.employees.employee[0].firstName
Upvotes: 1