BrianHicks / elm-csv / Csv.Encode

encode : { encoder : Encoder a, fieldSeparator : Char } -> List a -> String

Encode some data to a CSV string, quoting and escaping characters as necessary.


type Encoder a

Describe how you want the output CSV to be shaped. Constructe encoders with withFieldNames and withoutFieldNames.

withFieldNames : (a -> List ( String, String )) -> Encoder a

When provided a function that maps field names to values, this function uses it to produce a perfectly rectangular CSV.

[ ( "FF", "FF", "FF" )
, ( "80", "80", "80" )
, ( "00", "00", "00" )
]
    |> encode
        { encoder =
            withFieldNames
                (\( r, g, b ) ->
                    [ ( "red", r )
                    , ( "green", g )
                    , ( "blue", b )
                    ]
                )
        , fieldSeparator = ','
        }
    --> "red,green,blue\r\nFF,FF,FF\r\n80,80,80\r\n00,00,00"

The ordering of columns is determined by the order of values returned from the function.

withoutFieldNames : (a -> List String) -> Encoder a

Encode your data however you like. This is the "live an exciting adventure" encoder in that it will let you output rows with uneven lengths.

[ ( "FF", "FF", "FF" )
, ( "80", "80", "80" )
, ( "00", "00", "00" )
]
    |> encode
        { encoder = withoutFieldNames (\(r,g, b) -> [ r, g, b ] )
        , fieldSeparator = ','
        }
    --> "FF,FF,FF\r\n80,80,80\r\n00,00,00"