LoginSignup
13
8

More than 5 years have passed since last update.

Pythonで文字列がJsonフォーマットに則しているか判別する方法

Last updated at Posted at 2018-01-23

関数が受けた文字列や読みだしたファイルがJsonフォーマットであるか判定したい場合。

例外はjson.JSONDecodeErrorで捕まえられます。
ValueErrorでもキャッチできますがほかの例外もまとめられてしまうので基本的にはjson.JSONDecodeErrorで例外処理を行いましょう。

json_exception
def isJsonFormat(line):
    try:
        json.loads(line)
    except json.JSONDecodeError as e:
        print(sys.exc_info())
        print(e)
        return False
    # 以下の例外でも捕まえるので注意
    except ValueError as e:
        print(sys.exc_info())
        print(e)
        return False
    except Exception as e:
        print(sys.exc_info())
        print(e)
        return False
    return True

print(sys.exc_info())の出力
<class 'json.decoder.JSONDecodeError'>
JSONDecodeError('Extra data: line 1 column 5 (char 4)',)
<traceback object at 0x000002228CEAF1C8>

print(e)の出力
Extra data: line 1 column 5 (char 4)

13
8
2

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
13
8