LoginSignup
1
0

More than 1 year has passed since last update.

JSON形式を判定するツール(Python)

Posted at

概要

今日は前回のテストデータに含まれているデータがJSON形式が正しいか判定するツールを作成します。
業務上でこのファイルを毎回行毎にWEBサイトで貼り付けて確認するのが面倒でしたので、
Pythonで作成することになりました。

前回の記事

JSONファイルの日付のみ更新するツールです。

ファイルの内容

次の内容にレコードを追加しましょう。

#################
cur20200101.json
#################
{"name":"田中","age":"46","gender":"1","reg_date":"2020/01/01 15:33:25"}{ssss}
{"name":"鈴木","age":"32","gender":"1","reg_date":"2020/01/01 16:18:12"}
{"name":"水島","age":"52","gender":"1","reg_date":"2020/01/01 17:48:45"}{{{
{"name":"田中","age":"46","gender":"1","reg_date":"2020/01/02 22:33:25"}###@
{"name":"鈴木","age":"32","gender":"1","reg_date":"2020/01/02 23:18:12"}
{"name":"水島","age":"52","gender":"1","reg_date":"2020/01/02 23:48:45"}

ソース

現在ディレクトリにあるファイルからJSON形式の行を判定するロジックです。
正しくない場合、該当するファイル名とjsonの内容を表示します。

#!/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)
        result = True
    except Exception as e:
        print("file=" + filename)
        print("json=" + json_str)
        print("")

for file in os.listdir('./'):
    if file != 'check.py':
        with open(file) as f:
            for line in f:
                content = is_json(line, file)

実行

上記のコマンドを保存して実行します。

pi@raspberrypi:~/work/month=01/day=01 $ python check.py
file=cur20250101.json
json={"name":"田中","age":"46","gender":"1","reg_date":"2020/01/01 15:33:25"}{ssss}


file=cur20250101.json
json={"name":"水島","age":"52","gender":"1","reg_date":"2020/01/01 17:48:45"}{{{


file=cur20250101.json
json={"name":"田中","age":"46","gender":"1","reg_date":"2020/01/02 22:33:25"}###@


file=cur20250101.json
json=
#最後の行がそのまま判定されています。

終わりに

最初は手動でチェックしようとしましたが、どう考えても効率が悪いのでPythonでチェックしてから正しくないものを修正する方法で作業がおわりましたので、今回メモとして残しました。
次回は日付毎にファイルを保存するツールを作成したいと思います。
ありがとうございます。

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