LoginSignup
0
0

More than 1 year has passed since last update.

JSONデータチェック及び保存処理統合版(Python)

Last updated at Posted at 2022-07-26

概要

今日は前回の3つの記事で作成したPythonコードを1つにマージします。

前回の記事は下記のリンクを参照

①JSON形式を判定するツール(Python)
https://qiita.com/neomi/items/f0bfbaabc7598febba2f

②JSONデータを日付毎に保存(Python)
https://qiita.com/neomi/items/4badcd514d86721e1e7d

③JSONデータを日付フォルダ毎に保存(Python)
https://qiita.com/neomi/items/4c32db545c41652e360b

事前JSONデータファイル

次の内容通りにJSONファイルを保存してください。

pi@raspberrypi:~/work $ cat cur20200101.json
{"name":"田中","age":"46","gender":"1","reg_date":"2020/01/01 15:33:25"}aa
{"name":"鈴木","age":"32","gender":"1","reg_date":"2020/01/01 16:18:12"}bb
pi@raspberrypi:~/work $ cat cur20200201.json
{"name":"水島","age":"52","gender":"1","reg_date":"2020/02/01 17:48:45"}
pi@raspberrypi:~/work $ cat cur20200202.json
{"name":"田中","age":"46","gender":"1","reg_date":"2020/02/02 22:33:25"}
pi@raspberrypi:~/work $ cat cur20200302.json
{"name":"鈴木","age":"32","gender":"1","reg_date":"2020/03/02 23:18:12"}
{"name":"水島","age":"52","gender":"1","reg_date":"2020/03/02 23:48:45"}
pi@raspberrypi:~/work $

ソース

パス関連のライブラリを使いたいですが、今回はまた前回のバージョンそのまま利用します。
時間がある場合、再度修正します。

参照予定のライブラリ
https://docs.python.org/ja/3/library/pathlib.html#module-pathlib

次のコードを作成してtest.pyに保存します。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import json

def is_json(json_str, filename):
    result = False
    try:
        json.loads(json_str)
    except Exception as e:
        print("file=" + filename)
        print("json=" + json_str)
        print("")
        return 1
    return 0


cur_path = os.getcwd()

for file in os.listdir('./'):
    if file != 'test.py':
        with open(file) as f:
            for line in f:
                flag = is_json(line, file)                
                if (flag == 0):
                    content = line.split(',')
                    for item in content:
                        if(item.find('reg_date')>0):
                            print(item)
                            tmp = item.split('":"')
                            dd = tmp[1][0:10].replace("/","")
                            if(file.find('cur') == 0):
                                pre = "cur"
                            elif(file.find('xxx') == 0):
                                pre = "xxx"
                            else:
                                pre = "none"

                            monthdir = 'month=' + dd[4:6]
                            daydir = 'day=' + dd[6:8]

                            if(not os.path.exists(cur_path + "/data/")):
                                os.mkdir(cur_path + "/data/")

                            if(not os.path.exists(cur_path + "/data/" + monthdir)):
                                os.mkdir(cur_path + "/data/" + monthdir)

                            if(not os.path.exists(cur_path + "/data/" + monthdir + "/" + daydir)):
                                os.mkdir(cur_path + "/data/" + monthdir + "/" + daydir)

                            with open(cur_path + "/data/" + monthdir + "/" + daydir + "/" + pre + dd + ".json", 'a') as writer:
                                writer.write(line)

実行

上記のファイルを実行します。

# 実行前のディレクトリの確認
pi@raspberrypi:~/work $ ls -alh
合計 28K
drwxr-xr-x  2 pi pi 4.0K  7 26 13:02 .
drwxr-xr-x 23 pi pi 4.0K  6 28 10:58 ..
-rw-r--r--  1 pi pi  154  7 26 12:17 cur20200101.json
-rw-r--r--  1 pi pi   74  7 26 12:32 cur20200201.json
-rw-r--r--  1 pi pi   75  6 15 11:34 cur20200202.json
-rw-r--r--  1 pi pi  150  6 15 11:34 cur20200302.json
-rw-r--r--  1 pi pi 1.9K  7 26 12:56 test.py

# 正しくないJSONデータが保存されているファイル
pi@raspberrypi:~/work $ cat cur20200101.json
{"name":"田中","age":"46","gender":"1","reg_date":"2020/01/01 15:33:25"}aa
{"name":"鈴木","age":"32","gender":"1","reg_date":"2020/01/01 16:18:12"}bb

# 実行結果 ファイル名が表示されているのは正しくないJSONデータの行を表示している
pi@raspberrypi:~/work $ python test.py
file=cur20200101.json
json={"name":"田中","age":"46","gender":"1","reg_date":"2020/01/01 15:33:25"}aa


file=cur20200101.json
json={"name":"鈴木","age":"32","gender":"1","reg_date":"2020/01/01 16:18:12"}bb


pi@raspberrypi:~/work $ cat data/month\=02/day\=01/cur20200201.json
{"name":"水島","age":"52","gender":"1","reg_date":"2020/02/01 17:48:45"}
pi@raspberrypi:~/work $ cat data/month\=02/day\=02/cur20200202.json
{"name":"田中","age":"46","gender":"1","reg_date":"2020/02/02 22:33:25"}
pi@raspberrypi:~/work $ cat data/month\=03/day\=02/cur20200302.json
{"name":"鈴木","age":"32","gender":"1","reg_date":"2020/03/02 23:18:12"}
{"name":"水島","age":"52","gender":"1","reg_date":"2020/03/02 23:48:45"}
pi@raspberrypi:~/work $

保存されているディレクトリ内容

JSONデータの日付データに合わせて対象ディレクトリにJSONデータを集めて保存したファイルです。
image.png

最後に

前のJSONデータが正しいことのチェックとJSONデータの対象日付データのみ該当する日付ディレクトリに保存するものをまとめてコードを書いてみました。
まだディレクトリの指定が雑ですが、近いうちにまた修正したいと思います。
今日はここまでです。ありがとうございます。W

0
0
1

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
0