...

/

CSV Parsing: The CSV Parser

CSV Parsing: The CSV Parser

Take a look at the implementation of the CSV parser in our example application.

The CSV parser

We can now move on to implementing a CSV parser. Here is a possible implementation:

Press + to interact
defmodule Bday.Csv do
def encode([]), do: ""
def encode(maps) do
keys = 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")])
end
def 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))
end
end

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:

  1. encode/1
  2. decode/1.

The functions are fairly straightforward, delegating the more complex operations to private ...