1
0

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.

jsonファイルからディレクトリを生成するスクリプト

Last updated at Posted at 2020-03-15

はじめに

以下のようなjsonファイルがあったとします。

sample.json

{
    "data": [
        {
            "no": "1",
            "date": "2020-01-28T00:00",
            "place": "japan",
            "age": "22",
            "sex": "female"
        },
        {
            "no": "2",
            "date": "2020-02-14T00:00",
            "place": "australia",
            "age": "50",
            "sex": "male"
        }
    ],
    "last_update": "2020-03-14T23:14:01.849130+09:00"
}

このファイルから以下のようなディレクトリを生成するスクリプトです。

スクリーンショット 2020-03-15 16.42.01.png

keyとlistのindexで階層分けという事です。

json2dir

jsonファイルを再帰的に解析して、生成すべきdirectoryリストを返します。

sample.py
import json2dir

jsondict = {
# jsondictは前述のsample.jsonをdict型として読み込む
}

root_dir = 'api/sample'
os.makedirs(root_dir, exist_ok=True) #api/sampleというディレクトリを生成

# 本スクリプトによりディレクトリ一覧を生成
dirs = json2dir.dir_list_of(jsondict, root_dir)
'''
dir = ['api/sample/data', 'api/sample/data/0', 'api/sample/data/0/no', 'api/sample/data/0/date', 
'api/sample/data/0/place', 'api/sample/data/0/age', 'api/sample/data/0/sex', 'api/sample/data/1', 
'api/sample/data/1/no', 'api/sample/data/1/date', 'api/sample/data/1/place', 'api/sample/data/1/age', 
'api/sample/data/1/sex', 'api/sample/last_update']
'''

# api/sample以下に、dirに基づきディレクトリを生成
for d in dirs:
    os.makedirs(d, exist_ok=True)

以上でディレクトリが生成されます。

終わりに

ちなみにpipでjson-to-dirというパッケージが配布されていますが、(たぶん)Python2.x系で書かれててちゃんと動きませんでした(ので作りました)。
必要性がありそうならpipパッケージにしたいなって思っていますが、自分の必要性は満たせたのでとりあえず後回しにしています。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?