Last active
November 29, 2019 15:54
-
-
Save tommorris/d1e0be4222c6a12fc90fe6a6fe1529fa to your computer and use it in GitHub Desktop.
a really hacky version of DataGrip's JSON-Groovy.json.groovy to emit "line-oriented" JSON
This file contains 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
/* | |
* Available context bindings: | |
* COLUMNS List<DataColumn> | |
* ROWS Iterable<DataRow> | |
* OUT { append() } | |
* FORMATTER { format(row, col); formatValue(Object, col) } | |
* TRANSPOSED Boolean | |
* plus ALL_COLUMNS, TABLE, DIALECT | |
* | |
* where: | |
* DataRow { rowNumber(); first(); last(); data(): List<Object>; value(column): Object } | |
* DataColumn { columnNumber(), name() } | |
*/ | |
import static com.intellij.openapi.util.text.StringUtil.escapeStringCharacters as escapeStr | |
NEWLINE = "" | |
INDENT = "" | |
def printJSON(level, col, o) { | |
switch (o) { | |
case null: OUT.append("null"); break | |
case Number: OUT.append(FORMATTER.formatValue(o, col)); break | |
case Boolean: OUT.append("$o"); break | |
case String: OUT.append("\"${escapeStr(o)}\""); break | |
case Tuple: printJSON(level, o[0], o[1]); break | |
case Map: | |
OUT.append("{") | |
o.entrySet().eachWithIndex { entry, i -> | |
OUT.append("${i > 0 ? "," : ""}$NEWLINE${INDENT * (level + 1)}") | |
OUT.append("\"${escapeStr(entry.getKey().toString())}\"") | |
OUT.append(": ") | |
printJSON(level + 1, null, entry.getValue()) | |
} | |
OUT.append("$NEWLINE${INDENT * level}}") | |
break | |
case Object[]: | |
case Iterable: | |
OUT.append("[") | |
def plain = true | |
o.eachWithIndex { item, i -> | |
plain = item == null || item instanceof Number || item instanceof Boolean || item instanceof String | |
if (plain) OUT.append(i > 0 ? ", " : "") | |
else OUT.append("${i > 0 ? "," : ""}$NEWLINE${INDENT * (level + 1)}") | |
printJSON(level + 1, null, item) | |
} | |
if (plain) OUT.append("]") else OUT.append("$NEWLINE${INDENT * level}]") | |
break | |
default: | |
if (col != null) printJSON(level, null, FORMATTER.formatValue(o, col)) | |
else OUT.append("$o") | |
break | |
} | |
} | |
ROWS.transform { row -> | |
def map = new LinkedHashMap<String, String>() | |
COLUMNS.each { col -> | |
def val = row.value(col) | |
map.put(col.name(), new Tuple(col, val)) | |
} | |
map | |
}.each { row -> | |
printJSON(0, null, row) | |
OUT.append("\n") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment