2
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 3 years have passed since last update.

[jq] jqでcsvをjsonへ変換

Posted at

概要

jqコマンドを利用して1行目がヘッダ行のcsvをjsonのハッシュ配列へ変換する。

コマンド

$ cat sample.csv | jq -s -R '[split("\n")[]|select(length > 0)|split(",")|map(gsub("^\\s+|\\s+$";""))]|.[0] as $header | .[1:]|map([ $header, . ]|transpose|map({"key": (.[0]//""), "value": (.[1]//"")})|from_entries)'

sample.csv

record1,record2,record3,record4
L1R1,L1R2,L1R3,L1R4

L2R1,L2R2,L2R3,L2R4
  L3R1,L3R2  ,  L3R3  ,L3R4
L4R1,L4R2,,
,L5R2,L5R3

output

[
  {
    "record1": "L1R1",
    "record2": "L1R2",
    "record3": "L1R3",
    "record4": "L1R4"
  },
  {
    "record1": "L2R1",
    "record2": "L2R2",
    "record3": "L2R3",
    "record4": "L2R4"
  },
  {
    "record1": "L3R1",
    "record2": "L3R2",
    "record3": "L3R3",
    "record4": "L3R4"
  },
  {
    "record1": "L4R1",
    "record2": "L4R2",
    "record3": "",
    "record4": ""
  },
  {
    "record1": "",
    "record2": "L5R2",
    "record3": "L5R3",
    "record4": ""
  }
]

解説

# CSVファイルをjqに読み込み
$ cat sample.csv | jq -s -R '

    # 読み込んだcsvファイルから空行を除いて、各値の前後の空白を取り除き、[ [ "record1", "record2",..],["L1R1", "L1R2",..],..]の形に変換 
    [split("\n")[]|select(length > 0)|split(",")|map(gsub("^\\s+|\\s+$";""))]|

      # 1行目をヘッダー行として[ "record1", "record2",..]の形で保管しつつ、2行目以降をmapに送り1行ずつ処理する
      .[0] as $header | .[1:]|map(

        # ヘッダーと処理対象の行を一旦[ [ "record1", "record2",..],["L1R1", "L1R2",..] ] にまとめ、transposeで [ ["record1", "L1R1"], ["record2", "L1R2"] ]の形に変換する
        [ $header, . ]|transpose|

        # 各レコード、1項目目をkey,2項目目をvalueのハッシュへ変換する。 [ ["record1", "L1R1"],.. ] を [ { "key": "record1", "L1R1" },..]へ変換
        map({"key": (.[0]//""), "value": (.[1]//"")})|

        # 最後にfrom_entriesで目的のハッシュに変換する
        from_entries
      )'
2
2
0

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