The other day, I summarized how to read a json file with PowerShell, perform necessary formatting and output json, but since I tried it with Python, I would like to keep it as a memorandum.
First is the json file to read.
data.json
{
"prefectures": [
{
"code": "Tokyo",
"name": "Tokyo"
},
{
"code": "Osaka",
"name": "Osaka"
},
{
"code": "Aichi",
"name": "Aichi"
},
{
"code": "Fukuoka",
"name": "Fukuoka"
}
],
"tables": [
{
"code": "meeting_room",
"name": "conference room",
"field1": "id",
"field2": "floar",
"field3": "capacities"
},
{
"code": "parking",
"name": "Parking Lot",
"field1": "id",
"field2": "area",
"field3": "space_number",
"field4": "user_name",
"field5": "car_number",
"field6": "expire"
}
]
}
What I want to output is a json file for each item of prefectures x tables. In addition, the json adds the area code and area name to each of the table's code and name.
Here is the code I tried. I think that the contents of the for sentence on the 17th and 22nd lines can be organized more neatly, so I need to devote myself.
main.py
import os
import sys
import pathlib
import json
import itertools
def json_make():
"""
Output json for region x table type from Json data
"""
jsonfile = open('data.json', 'r')
data = json.load(jsonfile)
prefectures = data['prefectures']
tables = data['tables']
for pref, table in itertools.product(prefectures, tables):
pref_code = pref["code"]
pref_name = pref["name"]
result = {}
for k in table:
if k == 'code':
result['code'] = f'{pref_code}_{table[k]}'
elif k == 'name':
result['name'] = f'{pref_name}_{table[k]}'
else:
result[k] = table[k]
expfile = open("./results/" + result['code'] + '.json', 'w')
# ensure_ascii=Avoid Japanese encoding by adding False
json.dump(result, expfile, indent=4, ensure_ascii=False)
#Do not process if there is no file
if os.path.exists('data.json') is False:
sys.exit()
#Create if there is no output folder
exp = pathlib.Path('./results')
if exp.exists() is False:
exp.mkdir()
json_make()
naoki$ ls -l results
-rw-r--r-- 1 naoki staff 139 4 19 13:16 Aichi_meeting_room.json
-rw-r--r-- 1 naoki staff 214 4 19 13:16 Aichi_parking.json
-rw-r--r-- 1 naoki staff 141 4 19 13:16 Fukuoka_meeting_room.json
-rw-r--r-- 1 naoki staff 216 4 19 13:16 Fukuoka_parking.json
-rw-r--r-- 1 naoki staff 139 4 19 13:16 Osaka_meeting_room.json
-rw-r--r-- 1 naoki staff 214 4 19 13:16 Osaka_parking.json
-rw-r--r--@ 1 naoki staff 139 4 19 13:16 Tokyo_meeting_room.json
-rw-r--r-- 1 naoki staff 214 4 19 13:16 Tokyo_parking.json
Aichi_meeting_room.json
{
"code": "Aichi_meeting_room",
"name": "Aichi_conference room",
"field1": "id",
"field2": "floar",
"field3": "capacities"
}
Aichi_parking.json
{
"code": "Aichi_parking",
"name": "Aichi_Parking Lot",
"field1": "id",
"field2": "area",
"field3": "space_number",
"field4": "user_name",
"field5": "car_number",
"field6": "expire"
}
Recommended Posts