-1

i m trying to convert json into map as key value pair i have a method JsonSlurper() which give me the key value pair but my query is i have a json as bellow.

{"Result":"null",
"gbet":{"Qpet":[
{"msg":"MSG","over":"N","repair":[{"notification":null,"sce":"1","repair1":"CA","repairDes":null,"ran":1},
{"rep":"dvr"}],
{"msgger":"MSGwe","overw":"Ner"}]
}

how to get all the things in a single map with each key value pair i m doing like this

 def slurper = new JsonSlurper().parseText(str)

    log.info("sulpher"+slurper)
    def keys=slurper.keySet();
    log.info('keys'+keys)

but its not working for me i want each key and value pair as a separate field.

naval dogra
  • 9
  • 1
  • 7
  • 2
    could you please add a full example of what you want to have at the end. but beware: if you just want to flatten the map, there often is a reason why an api returns lists: there can be more than one result. – cfrick Mar 16 '15 at 08:59
  • i want like:-{"result":"null","msg":"MSG","over":"N","notifiacation":"null","sec":"1"} like all values should come in a single map – naval dogra Mar 16 '15 at 11:01
  • You know you'll lose any duplicate keys yeah? – tim_yates Mar 16 '15 at 11:25
  • yes for the time being i want only simple map without duplicate keys. i ll change the code,if u have please help... – naval dogra Mar 16 '15 at 12:15

2 Answers2

0

According to the JSON String you provided; It has only two parent keys i.e. Result and gbet. Where gbet has other nodes within it. You will have to fix your string or write you own method to flatten the string. There is no out of the box functionality available to achieve what you are asking for.

skis
  • 71
  • 1
  • 6
  • but i cannot able to do it because my key values are unknown to me this is just a sample json i have many more ,so i need a function which can create a map with key value pair...is it possible.? – naval dogra Mar 16 '15 at 16:06
0

You will have to implement your own flatten method. For example:

Map flattenMap(Map json) {
def result = [:]
json.each { k, v ->
    if (v instanceof Map) {
        result << flattenMap(v)
    } else if (v instanceof Collection && v.every {it instanceof Map}) {
        v.each { result << flattenMap(it) }
    } else {
        result[k] = v
    }
}
result
}

This example is using recursion so if it is nested too deeply it will overflow. It will not work on your sample because it is not valid json.

Dylan Bijnagte
  • 1,326
  • 9
  • 17