Decode values from CSV. This package tries to be as
unsurprising as possible, imitating elm/json and
[NoRedInk/elm-json-decode-pipeline][json-decode-pipeline] so that you can
apply whatever you already know about JSON decoders to a different data format.
Say you have a CSV like this:
ID,Name,Species
1,Atlas,cat
2,Axel,puffinYou want to get some data out of it, so you're looking through these docs. Where do you begin?
The first thing you need to know is that decoders are designed to fit together
to match whatever data shapes are in your CSV. So to decode the ID (an Int in
the "ID" field), you'd combine int and field like this:
data : String
data =
-- \u{000D} is the carriage return
"ID,Name,Species\u{000D}\n1,Atlas,cat\u{000D}\n2,Axel,puffin"
decodeCsv FieldNamesFromFirstRow (field "ID" int) data
--> Ok [ 1, 2 ]But this is probably not enough, so we'll need to combine a bunch of decoders
together using into:
decodeCsv FieldNamesFromFirstRow
(into
(\id name species ->
{ id = id
, name = name
, species = species
}
)
|> pipeline (field "ID" int)
|> pipeline (field "Name" string)
|> pipeline (field "Species" string)
)
data
--> Ok
--> [ { id = 1, name = "Atlas", species = "cat" }
--> , { id = 2, name = "Axel", species = "puffin" }
--> ]You can decode as many things as you want by giving into a function
that takes more arguments.
Decode a string.
decodeCsv NoFieldNames string "a" --> Ok [ "a" ]Unless you specify otherwise (e.g. with field) this will assume
there is only one column in the CSV and try to decode that.
decodeCsv NoFieldNames string "a,b"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = OnlyColumn
--> , problems = [ ExpectedOneColumn 2 ]
--> }
--> ]
--> )Decode an integer.
decodeCsv NoFieldNames int "1" --> Ok [ 1 ]
decodeCsv NoFieldNames int "volcano"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = OnlyColumn
--> , problems = [ ExpectedInt "volcano" ]
--> }
--> ]
--> )Unless you specify otherwise (e.g. with field) this will assume
there is only one column in the CSV and try to decode that.
decodeCsv NoFieldNames int "1,2"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = OnlyColumn
--> , problems = [ ExpectedOneColumn 2 ]
--> }
--> ]
--> )Decode a floating-point number.
decodeCsv NoFieldNames float "3.14" --> Ok [ 3.14 ]
decodeCsv NoFieldNames float "mimesis"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = OnlyColumn
--> , problems = [ ExpectedFloat "mimesis" ]
--> }
--> ]
--> )Unless you specify otherwise (e.g. with field) this will assume
there is only one column in the CSV and try to decode that.
decodeCsv NoFieldNames float "1.0,2.0"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = OnlyColumn
--> , problems = [ ExpectedOneColumn 2 ]
--> }
--> ]
--> )Handle blank fields by turning them into Maybes. We consider a field
to be blank if it's empty or consists solely of whitespace characters.
decodeCsv NoFieldNames (blank int) "\r\n1"
--> Ok [ Nothing, Just 1 ]Parse a value at a numbered column, starting from 0.
decodeCsv NoFieldNames (column 1 string) "a,b,c" --> Ok [ "b" ]
decodeCsv NoFieldNames (column 100 float) "3.14"
--> Err
--> (DecodingErrors
--> [ { row = 0
--> , column = Column 100
--> , problems = [ ColumnNotFound 100 ]
--> }
--> ]
--> )Parse a value at a named column. There are a number of ways to provide
these names, see FieldNames
decodeCsv
FieldNamesFromFirstRow
(field "Country" string)
"Country\r\nArgentina"
--> Ok [ "Argentina" ]Where do we get names for use with field?
NoFieldNames: don't get field names at all. field will
always fail.CustomFieldNames: use the provided field names in order (so ["Id", "Name"]
will mean that "Id" is in column 0 and "Name" is in column 1.)FieldNamesFromFirstRow: use the first row of the CSV as the source of
field names.Convert a CSV string into some type you care about using the
Decoders in this module!
Convert something shaped roughly like a CSV. For example, to decode a TSV (tab-separated values) string:
decodeCustom { fieldSeparator = '\t' }
NoFieldNames
(map2 Tuple.pair
(column 0 int)
(column 1 string)
)
"1\tBrian\n2\tAtlas"
--> Ok [ ( 1, "Brian" ), ( 2, "Atlas" ) ]Sometimes we cannot decode every row in a CSV. This is how we tell
you what went wrong. If you need to present this to someone, you can get a
human-readable version with errorToString
Some more detail:
ParsingError: there was a problem parsing the CSV into rows and
columns. All these errors have to do with quoting issues. Check that
any quoted fields are closed and that quotes are escaped.NoFieldNamesOnFirstRow: we tried to get the field names from the first
row (using FieldNames) but couldn't find any, probably
because the input was blank.DecodingErrors: we couldn't decode a value using the specified
decoder. See Problem for more details.Produce a human-readable version of an Error?!
Where did the problem happen?
Column: at the given column numberField: at the given named column (with optional column number if we were
able to look up what column we should have found.)OnlyColumn: at the only column in the rowThings that can go wrong while decoding:
ColumnNotFound Int and FieldNotFound String: we looked for the
specified column, but couldn't find it. The argument specifies where we
tried to look.FieldNotProvided String: we looked for a specific field, but it wasn't
present in the first row or the provided field names (depending on your
configuration.)ExpectedOneColumn Int: basic decoders like string and
int expect to find a single column per row. If there are multiple
columns, and you don't specify which to use with column
or field, you'll get this error. The argument says how many
columns we found.ExpectedInt String and ExpectedFloat String: we failed to parse a
string into a number. The argument specifies the string we got.Failure: we got a custom failure message from fail.Transform a decoded value.
decodeCsv NoFieldNames (map (\i -> i * 2) int) "15"
--> Ok [ 30 ]
decodeCsv NoFieldNames (map String.reverse string) "slap"
--> Ok [ "pals" ]Combine two decoders to make something else.
decodeCsv NoFieldNames
(map2 Tuple.pair
(column 0 int)
(column 1 string)
)
"1,Atlas"
--> Ok [ (1, "Atlas") ]Combine an arbitrary amount of fields. You provide a function that takes
as many arguments as you need, then send it values by providing decoders with
pipeline.
type alias Pet =
{ id : Int
, name : String
, species : String
, weight : Float
}
petDecoder : Decoder Pet
petDecoder =
into Pet
|> pipeline (column 0 int)
|> pipeline (column 1 string)
|> pipeline (column 2 string)
|> pipeline (column 3 float)Now you can decode pets like this:
decodeCsv NoFieldNames petDecoder "1,Atlas,cat,14\r\n2,Axel,puffin,1.37"
--> Ok
--> [ { id = 1, name = "Atlas", species = "cat", weight = 14 }
--> , { id = 2, name = "Axel", species = "puffin", weight = 1.37 }
--> ]Try several possible decoders in sequence, committing to the first one that passes.
decodeCsv NoFieldNames
(oneOf
(map Just int)
[ succeed Nothing ]
)
"1"
--> Ok [ Just 1 ]
decodeCsv NoFieldNames
(oneOf
(map Just int)
[ succeed Nothing ]
)
"a"
--> Ok [ Nothing ]Decode some value and then make a decoding decision based on the outcome. For example, if you wanted to reject negative numbers, you might do something like this:
positiveInt : Decoder Int
positiveInt =
int
|> andThen
(\rawInt ->
if rawInt < 0 then
Decode.fail "Only positive numbers allowed!"
else
Decode.succeed rawInt
)You could then use it like this:
decodeCsv NoFieldNames positiveInt "1" -- Ok [ 1 ]
decodeCsv NoFieldNames positiveInt "-1"
-- Err { row = 0, problem = Failure "Only positive numbers allowed!" }Always fail with the given message, no matter what. Mostly useful with
andThen.
Make creating custom decoders a little easier. If you already have a function that parses into something you care about, you can combine it with this.
For example, here's how you could parse a hexadecimal number with
rtfeldman/elm-hex:
import Hex
hex : Decoder Int
hex =
andThen
(\value -> fromResult (Hex.fromString value))
string
decodeCsv NoFieldNames hex "ff"
--> Ok [ 255 ]Like fromResult but you have to specify the error
message since Nothing has no further information.
For example, you could implement something like int using this:
myInt : Decoder Int
myInt =
andThen
(\value ->
fromMaybe "Expected an int"
(String.toInt value)
)
string
decodeCsv NoFieldNames myInt "123"
--> Ok [ 123 ](That said, you probably want to use int instead... it has better
error messages and is more tolerant of unusual situations!)
A way to specify what kind of thing you want to decode into. For example, if you have a
Petdata type, you'd want aDecoder Pet.