Migrate data from .csv to .yml

K

Kamarulnizam Rahim

Hi,

Does anyone has any parsers or examples or guidelines on how to convert
csv data into YAML (.yml) format? I counldnt find any appropriate
guideline that explains how to do this. Any link or example that
explains how to do this is welcomed. Thanks

Nizam
 
J

Johnny Morrice

Hi,

Does anyone has any parsers or examples or guidelines on how to
convert csv data into YAML (.yml) format? I counldnt find any
appropriate guideline that explains how to do this. Any link or
example that explains how to do this is welcomed. Thanks

Nizam

First you need to parse the CSV, using the standard library.
Then you need to attribute some sort of semantic meaning to it. I'd do
this by arranging it into data structures.
Then you would convert it to yaml, again using the standard library.

Here is an example, tested with ruby 1.8.7.

It converts a CSV database into an array of maps, and then serializes
it to YAML.

http://pastebin.com/nJMy0Fun

Have fun,
Johnny
 
B

brabuhr

Does anyone has any parsers or examples or guidelines on how to convert
csv data into YAML (.yml) format? I counldnt find any appropriate
guideline that explains how to do this. Any link or example that
explains how to do this is welcomed. Thanks

Bare bones:

irb(main):001:0> require 'csv'
=> true
irb(main):002:0> z = CSV.read('foo.csv', :headers => true)
=> #<CSV::Table mode:col_or_row row_count:4>
irb(main):003:0> require 'yaml'
=> true
irb(main):004:0> puts z.to_yaml
--- !ruby/object:CSV::Table
mode: :col_or_row
table:
- !ruby/object:CSV::Row
header_row: false
row:
- - a
- "1"
- - b
- "2"
- - c
- "3"
- !ruby/object:CSV::Row
header_row: false
row:
- - a
- "4"
- - b
- "5"
- - c
- "6"
- !ruby/object:CSV::Row
header_row: false
row:
- - a
- "7"
- - b
- "8"
- - c
- "9"

Though, I imagine you have some other idea of how the yaml should be
structured; so, the idea could be to loop through each row in the CSV,
build e.g. a Hash that looks like what you want, append that hash to
an Array, and then dump that Array to_yaml. (Somewhat like what
Johnny posted while I was typing this paragraph :)
 
K

Kamarulnizam Rahim

Thanks for the info guys. Right now i am still trying to read my csv
file. I will look through your material afterwards. n maybe will ask few
more question regarding this cause i am pretty sure i will encounter
some other prob later. Really appreciate your helps. Thanks

Nizam
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top