beatrichartz / csv

CSV Decoding and Encoding for Elixir
MIT License
494 stars 91 forks source link

Support for csv in strings? #23

Closed gouthamvel closed 8 years ago

gouthamvel commented 8 years ago

I'm getting a error when trying to use csv on strings rather than reading from file

iex(23)> string = "a,1
...(23)> b,4"
"a,1\nb,4"
iex(24)> string |> CSV.decode  |> Enum.map fn r -> Enum.map(r, &String.upcase/1) end
** (Protocol.UndefinedError) protocol Enumerable not implemented for "a,1\nb,4"
    (elixir) lib/enum.ex:1: Enumerable.impl_for!/1
    (elixir) lib/enum.ex:112: Enumerable.reduce/3
    (elixir) lib/stream.ex:1240: Enumerable.Stream.do_each/4
    (elixir) lib/stream.ex:700: Stream.do_transform/8
    (elixir) lib/enum.ex:1400: Enum.reduce/3
    (elixir) lib/enum.ex:1047: Enum.map/2
iex(24)> File.stream!("/Users/username/test_data.csv") |> CSV.decode  |> 
iex(25)>Enum.map fn r -> Enum.map(r, &String.upcase/1) end
[["A", "1"], ["B", "4"]]
iex(26)>

the contents of test_data.csv are same as string used Is there anything wrong i'm doing or are strings not supported?

PS: i'm fairly new to functional programing/elixir world.

beatrichartz commented 8 years ago

The input to CSV is required to be enumerable - that means if you have a string you could e.g. split it by line with String.split:

string = "a,1\nb,4"
string |> String.split("\n") |> CSV.decode  |> Enum.map fn r -> Enum.map(r, &String.upcase/1) end

Curious, what's the exact usecase?

gouthamvel commented 8 years ago

Its working thanks.