Skip to content

Instantly share code, notes, and snippets.

@KentaYamada
Last active June 4, 2017 12:17
Show Gist options
  • Select an option

  • Save KentaYamada/f469c6b02f898cbfde345076dccca2ff to your computer and use it in GitHub Desktop.

Select an option

Save KentaYamada/f469c6b02f898cbfde345076dccca2ff to your computer and use it in GitHub Desktop.
json file I/O for python3
# -*-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.")
{
"name": "Taro",
"age": 24,
"japanese": "たろう"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment