Last active
June 4, 2017 12:17
-
-
Save KentaYamada/f469c6b02f898cbfde345076dccca2ff to your computer and use it in GitHub Desktop.
json file I/O for python3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -*-coding: utf-8 -*- | |
| import os | |
| import json | |
| def read_json(filename): | |
| if not os.path.isfile(filename): | |
| raise FileExistsError("[error] {0} not found.".format(filename)) | |
| with open(filename) as f: | |
| return json.load(f) | |
| def write_json(obj, filename): | |
| if obj is None: | |
| raise ValueError("[error] obj parameter cannot null.") | |
| if not isinstance(obj, dict): | |
| raise TypeError("[error] obj type must be dictionary.") | |
| with open(filename, mode='w') as f: | |
| json.dump(obj, f, ensure_ascii=False) | |
| if __name__ == '__main__': | |
| jsonStr = read_json("./test.json") | |
| print(jsonStr) | |
| try: | |
| write_json(jsonStr, "./write_test.json") | |
| print("success") | |
| except Exception as e: | |
| print("failed.") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| { | |
| "name": "Taro", | |
| "age": 24, | |
| "japanese": "たろう" | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment