Skip to content

Instantly share code, notes, and snippets.

@nicl
Last active December 17, 2015 03:09
Show Gist options
  • Save nicl/5541327 to your computer and use it in GitHub Desktop.
Save nicl/5541327 to your computer and use it in GitHub Desktop.
Convert data table string into usable form
/**
* Convert a dataTable string representation into a List of Maps. For example:
*
* | x | y |
* | 1 | a is |
* | 2 | b does |
*
* Becomes:
*
* List(Map(x -> 1, y -> "a is"), Map(x -> 2, y -> "b does"))
*/
def tableFromString(data: String): List[Map[String, String]] = {
def trimEach(seq: Array[String]): Array[String] = seq map { _.trim }
val lines = data split("\n") map { _.trim } map { _.drop(1) } map { _.dropRight(1) }
// split into lines, then for each remove surrounding whitespace and '|' chars
val cellsByLine = lines map { _.split('|') } map trimEach
val headerCells = cellsByLine.head
val rowCells = cellsByLine.tail
rowCells.toList map { row => headerCells.zip(row).toMap }
}
@nicl
Copy link
Author

nicl commented May 9, 2013

Note, this is not an exact equivalent of data tables. For example, at the moment this strips out all whitespace from the table. In the following example:

| col      |
| my value |

'my value' will become 'myvalue'.

@nicl
Copy link
Author

nicl commented Jul 3, 2013

UPDATE: this now handles whitespace correctly so the previous comment can be ignored.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment