Migrate data from .csv to .yml

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

···

--
Posted via http://www.ruby-forum.com/.

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.

Have fun,
Johnny

···

On Wed, 12 Jan 2011 09:49:18 +0900 Kamarulnizam Rahim <niezam54@hotmail.com> wrote:

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

I phrased on of the comments in that example much better here:
http://pastebin.com/3qK6JnWT

Ahh, tiredness.

···

On Wed, 12 Jan 2011 09:49:18 +0900 Kamarulnizam Rahim <niezam54@hotmail.com> wrote:

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 :slight_smile:

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

···

--
Posted via http://www.ruby-forum.com/.