Last active
May 9, 2017 07:00
-
-
Save raza-basit/6abfb23ef1643f4fa1056f1d300538c8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import groovy.json.JsonSlurper | |
import groovy.json.JsonOutput | |
def formatJson(json) { | |
def obj = new JsonSlurper().parseText(json) | |
def map = [:] | |
if(obj instanceof Map) { | |
obj.each { | |
def tmp = [:] | |
def tmpKey = "$it.key" | |
if(tmpKey.contains(".")) { | |
def parent_key = tmpKey.substring(0, tmpKey.indexOf(".")) | |
def sub_key = tmpKey.substring(tmpKey.indexOf(".") + 1) | |
// if(!map.containsKey(parent_key)) { | |
tmp = formatJson(JsonOutput.toJson(["$sub_key" : it.value])) | |
if(!map.containsKey(parent_key)) | |
map.put(parent_key, tmp) | |
else { | |
prev_val = map.get(parent_key) | |
tmp.each { | |
if(prev_val.containsKey(it.key)) { | |
sub_map = prev_val.get(it.key) | |
another_map = tmp.get(it.key) | |
sub_map = process_nested(another_map, sub_map) | |
prev_val.put(it.key, sub_map) | |
} | |
else | |
prev_val.put(it.key, it.value) | |
} | |
map.put(parent_key, prev_val) | |
} | |
} else { | |
map.put(it.key, it.value) | |
} | |
} | |
return map; | |
} | |
} | |
def process_nested(another_map, sub_map){ | |
another_map.each { | |
if(it.value instanceof Map ){ | |
sub_map.put(it.key,process_nested(it.value, sub_map.get(it.key))) | |
}else{ | |
sub_map.put(it.key, it.value) | |
} | |
} | |
return sub_map | |
} | |
def screwy = "{\"flip.flop.grab.hello.abc\": \"this\", \"tick.tock\": \"that\", \"flip.switch\" : \"swatch\", \"flip.flop.grab.hello.pick\": \"another\"}" | |
println JsonOutput.toJson(formatJson(screwy)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment