CSV Parsing: The CSV Parser
Take a look at the implementation of the CSV parser in our example application.
We'll cover the following...
The CSV parser
We can now move on to implementing a CSV parser. Here is a possible implementation:
Press + to interact
defmodule Bday.Csv dodef encode([]), do: ""def encode(maps) dokeys = Enum.map_join(Map.keys(hd(maps)), ",", &escape(&1))vals =for map <- maps, do: Enum.map_join(Map.values(map), ",", &escape(&1))to_string([keys, "\r\n", Enum.join(vals, "\r\n")])enddef decode(""), do: []def decode(csv) do{headers, rest} = decode_header(csv, [])rows = decode_rows(rest)for row <- rows, do: Map.new(Enum.zip(headers, row))endend
Note: Decoding is done by fetching the headers, then fetching all of the rows. A header line is parsed by reading each column name one at a time, and a row is parsed by reading each field one at a time.
First, there’s the public interface with two functions:
encode/1
decode/1
.
The functions are fairly straightforward, delegating the more complex operations to private ...