6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

awkを使ってcsvファイルをjson化

Last updated at Posted at 2017-07-26

ひさびさにawkを書いたのでqiitaに書き留めておきます。(最近はawsコマンドの方がよく使ってたりして)

csvデータをWeb系のアプリでハンドリングしやすくするためにJSON化して渡す必要があったので、awkでなんとかしてみました。

csv_to_json.awk
BEGIN{
  FS=","
  json="["
}
{
  if(NR==1){
    for(i=1;i<=NF;i++){
      keys[i]=$i
    }
  }else{
    json=json sprintf(NR>2?",{":"{")
    for(i=1;i<=NF;i++){
      json=json sprintf("\"%s\":\"%s\"",keys[i],$i)
      json=json sprintf(i<NF?",":"")
    }
    json=json "}"
  }
}
END{
  json=json "]"
  print json
}

ケツカンマの対処のための分岐がなんともしがたいですが、これを使えばサクッとJSON化できますよ。

$ cat test.csv
hoge,fuga
123,abc
456,def
$ awk -f csv_to_json.awk test.csv | jq '.'
[
  {
    "hoge": "123",
    "fuga": "abc"
  },
  {
    "hoge": "456",
    "fuga": "def"
  }
]

JSONの整形についてはjqに任せちゃいましょう

6
2
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
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?