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
-module(bday_csv).-export([encode/1, decode/1]).%% @doc Take a list of maps with the same keys and transform them%% into a string that is valid CSV, with a header.-spec encode([map()]) -> string().encode([]) -> "";encode(Maps) ->Keys = lists:join(",", [escape(Name) || Name <- maps:keys(hd(Maps))]),Vals = [lists:join(",", [escape(Field) || Field <- maps:values(Map)])|| Map <- Maps],lists:flatten([Keys, "\r\n", lists:join("\r\n", Vals)]).%% @doc Take a string that represents a valid CSV data dump%% and turn it into a list of maps with the header entries as keys-spec decode(string()) -> list(map()).decode("") -> [];decode(CSV) ->{Headers, Rest} = decode_header(CSV, []),Rows = decode_rows(Rest),[maps:from_list(lists:zip(Headers, Row)) || Row <- Rows].
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 ...
Access this course and 1400+ top-rated courses and projects.