LoginSignup
0
2

More than 1 year has passed since last update.

CSVファイルをJSONファイルに変換する ~ pythonの場合 ~

Last updated at Posted at 2021-10-17
  • CSVファイルをJSONファイルに変換する
  • 出力ファイル名とインデントの数(半角スペースの数)をパラメータで設定したい

コード

こちらのサイトのものを改造させていただきました
https://hktech.hatenablog.com/entry/2018/09/10/235725

import json
import csv
import click
import os


@click.command()
@click.argument('in_file')
@click.option('--out_file', '-o', default='', help='Output JSON file')
@click.option('--indent', '-i', default=0, help='JSON indent')
def main(in_file, out_file, indent):

    # CSV ファイルの読み込み
    json_list = []
    with open(in_file, 'r') as f:
        for row in csv.DictReader(f):
            json_list.append(row)

    # JSON ファイルへの書き込み
    out_file = get_outfile_name(in_file, out_file)

    with open(out_file, 'w') as f:
        if indent == '':
            json.dump(json_list, f, ensure_ascii=False)
            # 非ASCII文字(日本語とか)が含まれている場合に
            # そのまま出力するには ensure_ascii=Falseを指定します。
        else:
            json.dump(json_list, f, indent=indent, ensure_ascii=False)

# 出力ファイル名設定
# out_fileが未指定の場合はin_fileの拡張子をjsonに変更したものとする
def get_outfile_name(in_file, out_file):
    if out_file == '':
        return os.path.splitext(os.path.basename(in_file))[0] + '.json'
    else:
        return out_file

if __name__ == '__main__':
    main()

実行結果

入力ファイル

"id","name"
1,"foo"
2,"baa"

インデント無し、ファイル名未指定

$ python3 main.py sample.csv
# sample.json
[{"id": "1", "name": "foo"}, {"id": "2", "name": "baa"}]

インデント4 ファイル名指定

$ python3 main.py sample.csv -o output.json -i 4
# output.json
[
    {
        "id": "1",
        "name": "foo"
    },
    {
        "id": "2",
        "name": "baa"
    }
]

補足

  • いちいちpythonコマンドで実行するのは面倒なので、poetryを使ってパッケージ化 & pip installしてどこからでも使えるようにしています。
0
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
0
2