LoginSignup
0
1

More than 3 years have passed since last update.

Pythonでjsonファイルを読み込んで、整形して、json出力

Last updated at Posted at 2020-04-19

この前、PowerShellでjsonファイルを読み込み、必要な整形を行いjson出力する方法をまとめましたが、Pythonでやってみたので、備忘録として残しておきたいと思います。

前回のPowerShellで行ったコード

まず読み込むjsonファイルです。

data.json
{
    "prefectures": [
        {
            "code": "Tokyo",
            "name": "東京"
        },
        {
            "code": "Osaka",
            "name": "大阪"
        },
        {
            "code": "Aichi",
            "name": "愛知"
        },
        {
            "code": "Fukuoka",
            "name": "福岡"
        }
    ],
    "tables": [
        {
            "code": "meeting_room",
            "name": "会議室",
            "field1": "id",
            "field2": "floar",
            "field3": "capacities"
        },
        {
            "code": "parking",
            "name": "駐車場",
            "field1": "id",
            "field2": "area",
            "field3": "space_number",
            "field4": "user_name",
            "field5": "car_number",
            "field6": "expire"
        }
    ]
}

出力したいのは、prefectures x tablesの各item事のjsonファイルです。
また、そのjsonはtablesのcode, nameそれぞれに地域コード、地域名を追加します。

完成形のコード

やってみたコードはこちらです。
17行目と22行目のfor文の中身がもっと綺麗にまとめられると思っているので、精進が必要ですね。

main.py
import os
import sys
import pathlib
import json
import itertools


def json_make():
    """
    Jsonデータから地域 x テーブル種類分のjsonを出力
    """
    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=Falseをつけることで、日本語エンコードを回避
        json.dump(result, expfile, indent=4, ensure_ascii=False)


# ファイルがなければ処理しない
if os.path.exists('data.json') is False:
    sys.exit()

# 出力フォルダがなければ作成
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": "愛知_会議室",
    "field1": "id",
    "field2": "floar",
    "field3": "capacities"
}
Aichi_parking.json
{
    "code": "Aichi_parking",
    "name": "愛知_駐車場",
    "field1": "id",
    "field2": "area",
    "field3": "space_number",
    "field4": "user_name",
    "field5": "car_number",
    "field6": "expire"
}
0
1
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
1