Suppose you have a json file like this:
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"
}
A script that creates the following directories from this file.
It means that the hierarchy is divided by the index of key and list.
json2dir https://github.com/Kanahiro/json2dir
Recursively parses the json file and returns a list of directories to generate.
sample.py
import json2dir
jsondict = {
#jsondict is the sample mentioned above.Read json as dict type
}
root_dir = 'api/sample'
os.makedirs(root_dir, exist_ok=True) #api/Create a directory called sample
#Generate a directory list with this script
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/Create a directory based on dir under sample
for d in dirs:
os.makedirs(d, exist_ok=True)
The directory is created.
By the way, a package called json-to-dir is distributed by pip, but (probably) it was written in Python 2.x series and did not work properly (so I made it). I'd like to make it a pip package if there seems to be a need, but I've met my needs so I'm putting it off for the time being.
Recommended Posts