LoginSignup
3
9

More than 5 years have passed since last update.

tsv,csv,jsonの変換

Posted at

次のようなtsv,csv,jsonを変換するプログラミングをしました。

meibo.txt
john    m   18
paul    m   20
alice   f   15
dabid   m   17
jasmin  f   17
meibo.csv
john,m,18
paul,m,20
alice,f,15
dabid,m,17
jasmin,f,17
meibo.json
[{"name":"john","gender":"m","age":"18"},
 {"name":"paul","gender":"m","age":"20"},
 {"name":"alice","gender":"f","age":"15"},
 {"name":"dabid","gender":"m","age":"17"},
 {"name":"jasmin","gender":"f","age":"17"}]
  • tsv→csv

Rubyにはarrayに要素を追加するのに<<でできるんですね、なかなか便利そう。

tsv_to_csv.rb
require 'csv'
meibo_array =[]
File.foreach("meibo2.txt") do |line|
  meibo_array << line.chomp.split("\t")
end
CSV.open("meibo2.csv","w") do |csv|
  meibo_array.each do |person|
    csv << person
  end
end
  • json→tsv
json_to_tsv.rb
require 'json'
File.open("meibo.json") do |file|
  hash = JSON.load(file)
  File.open("meibo_from_json.txt","w") do |text|
    hash.each do |person|
      data = [person["name"],person["gender"],person["age"]]
      text.puts(data.join("\t"))
      #text.puts(person.values.join("\t"))
      #キーの順番に依存するのでよくない
    end
  end
end

最初はコメントアウトしてあるコードで書いてたんですが、jsonはkeyの順番を保証せず、
{"name":"john","gender":"m","age":"19"} と
{"name":"john","age":"19","gender":"m"}を区別しないようなので
tsvにする時はkeyをちゃんと指定してあげる必要があるようです。

  • tsv→tsv
tsv_to_json.rb
require 'json'
File.open("meibo_from_tsv.json","w") do |file|
  keys=["name","gender","age"]
  hash_array=[]
  File.foreach("meibo.txt") do |line|
    array = [keys,line.chomp.split("\t")].transpose
    hash_array << Hash[*array.flatten]
  end
  JSON.dump(hash_array,file)
end

これで作ったjsonを見やすく表示するにはjqコマンドを使用するようです。

$ jq . meibo_from_tsv.json

または

$ cat meibo_from_tsv.json | jq

今回ので
do |value| 処理 end
の書き方に結構慣れた気がする。

次は標準入出力を使って

$ ruby json_to_tsv.rb < meibo.json >meibo.txt

のようにして、プログラム内でFile.openしないプログラムを書きます。標準入出力しっかり理解しなきゃ。

3
9
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
9