created: 2018-11-03T08:24:38.000Z

GoogleSpreadsheetのデータ(csv)をパパッとjsonにしてスクリプトから使う

csvjsonを使うとcsv => json が簡単に変換できる csvjsonはcsvkitをインストールすると入ってくる

$ brew install csvkit
...
$ which csvjson
/usr/local/bin/csvjson

csvでダウンロード

Google SpreadSheetからcsv形式でダウンロード

  • ファイル
    • 形式を指定してダウンロード
      • カンマ区切りの値

image

csvjsonはデフォルトだとa, b といったキー名のオブジェクトを配列で作ってくれる

$ cat ~/Downloads/テストのデータ\ -\ シート1\ \(1\).csv | csvjson -H | jq .
[
  {
    "a": null,
    "b": "TOKIO",
    "c": 1
  },
  {
    "a": null,
    "b": "SMAP",
    "c": 2
  },
  {
    "a": null,
    "b": "嵐",
    "c": 0
  }
]

スクリプト

あとはjsonをスクリプトで使う
perlだとjsonのdecodeはこんな感じ

#!/usr/bin/perl
use JSON qw'decode_json';
my $input = decode_json join("", <STDIN>);
print "group arrested counts: " map {$_->{c}} @$input;

パイプで繋げばスプレッドシートのデータをスクリプトで操作できる

$ cat ~/Downloads/テストのデータシート1.csv | csvjson -H | ./myscript.pl
-H
$ csvjson --help | grep '\-H'
  -H, --no-header-row   Specify that the input CSV file has no header row.

もうちょっとインタラクティブに

スプレッドシートの権限をゆるくすればcurlでcsvを取ったりも出来る

$ curl -s https://docs.google.com/spreadsheets/d/xxxxxxx/export?format=csv \
    | csvjson -H | ./myscript.pl
アイリスオーヤマ ワイヤレス テレビ チューナー 地デジ/BS/CS 録画予約可能 LUCAステーション IST-BAUL201
[ad] アイリスオーヤマ ワイヤレス テレビ チューナー 地デジ/BS/CS 録画予約可能 LUCAステーション IST-BAUL201
アイリスオーヤマ(IRIS OHYAMA) (エレクトロニクス)