JSON-Groovy.json.groovy 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * Available context bindings:
  3. * COLUMNS List<DataColumn>
  4. * ROWS Iterable<DataRow>
  5. * OUT { append() }
  6. * FORMATTER { format(row, col); formatValue(Object, col) }
  7. * TRANSPOSED Boolean
  8. * plus ALL_COLUMNS, TABLE, DIALECT
  9. *
  10. * where:
  11. * DataRow { rowNumber(); first(); last(); data(): List<Object>; value(column): Object }
  12. * DataColumn { columnNumber(), name() }
  13. */
  14. import static com.intellij.openapi.util.text.StringUtil.escapeStringCharacters as escapeStr
  15. NEWLINE = System.getProperty("line.separator")
  16. INDENT = " "
  17. def printJSON(level, col, o) {
  18. switch (o) {
  19. case null: OUT.append("null"); break
  20. case Number: OUT.append("$o"); break
  21. case Boolean: OUT.append("$o"); break
  22. case String: OUT.append("\"${escapeStr(o)}\""); break
  23. case Tuple: printJSON(level, o[0], o[1]); break
  24. case Map:
  25. OUT.append("{")
  26. o.entrySet().eachWithIndex { entry, i ->
  27. OUT.append("${i > 0 ? "," : ""}$NEWLINE${INDENT * (level + 1)}")
  28. OUT.append("\"${escapeStr(entry.getKey().toString())}\"")
  29. OUT.append(": ")
  30. printJSON(level + 1, null, entry.getValue())
  31. }
  32. OUT.append("$NEWLINE${INDENT * level}}")
  33. break
  34. case Object[]:
  35. case Iterable:
  36. OUT.append("[")
  37. def plain = true
  38. o.eachWithIndex { item, i ->
  39. plain = item == null || item instanceof Number || item instanceof Boolean || item instanceof String
  40. if (plain) OUT.append(i > 0 ? ", " : "")
  41. else OUT.append("${i > 0 ? "," : ""}$NEWLINE${INDENT * (level + 1)}")
  42. printJSON(level + 1, null, item)
  43. }
  44. if (plain) OUT.append("]") else OUT.append("$NEWLINE${INDENT * level}]")
  45. break
  46. default:
  47. if (col != null) printJSON(level, null, FORMATTER.formatValue(o, col))
  48. else OUT.append("$o")
  49. break
  50. }
  51. }
  52. printJSON(0, null, ROWS.transform { row ->
  53. def map = new LinkedHashMap<String, String>()
  54. COLUMNS.each { col ->
  55. def val = row.value(col)
  56. map.put(col.name(), new Tuple(col, val))
  57. }
  58. map
  59. })