The space is in the input data, so carries through to the result
String output = new JsonBuilder( result.groupBy { it.Date }
.collect { key, value ->
value.collectEntries()
} ).toString()
And should the "Date": "2013-11-12 00:00", entry be getting default values as well?
Why not insert a dummy entry with all the required fields and ensure to be the first element in the list after sort. Then merge it with the second one:
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder
import groovy.json.JsonOutput
def json = """[ here comes the JSON string ] """
def order = [ 'Date':0, 'AVG':1, 'COMPLETED':2, 'ABORTED':3].withDefault { 9999 }
def parsed = new JsonSlurper().parseText(json)
// insert dummy entry and sort
// Date value ensures this entry comes first after sort
def dummy = [Date: -1, AVG: 0, COMPLETED: 0, ABORTED: 0]
def sorted = (parsed + dummy).sort { it.Date }
// merge 1st and 2nd entry
def merged = [sorted.take(2).collectEntries()] + sorted.drop(2)
// the rest is business as usual
def processed = merged.groupBy { it.Date }.collect { key, value ->
value.collectEntries().sort { order[it.key] }
}
String mergedJSON = new JsonBuilder( processed ).toString()
println new JsonOutput().prettyPrint(mergedJSON)
Cheers,
Dinko
Dinko,I get an error when I try to run the above script
Caught: groovy.json.JsonException: Unable to determine the current character, it is not a string, number, array, or objectThe current character read is 'h' with an int value of 104Unable to determine the current character, it is not a string, number, array, or objectline number 1index number 2[ here comes the JSON string ]..^groovy.json.JsonException: Unable to determine the current character, it is not a string, number, array, or object