Created
April 3, 2015 12:09
-
-
Save poppe1219/71e32e1a6aeff3e0f1a0 to your computer and use it in GitHub Desktop.
Example of reading and writing json files, using utf-8 endcoding.
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 -*- | |
"""Json file module.""" | |
import os | |
import json | |
import logging | |
logger = logging.getLogger() | |
def read_json_from_file(file_path): | |
"""Reads and de-serializes a json structure from a file.""" | |
json_structure = {} | |
try: | |
if file_path and os.path.isfile(file_path): | |
with open(file_path, "r") as handle: | |
content = handle.read() | |
if content is not None: | |
try: | |
json_structure = json.loads(content) | |
except Exception as exc: | |
logger.error( | |
'Could not de-serializes json: {}'.format(exc) | |
) | |
except Exception as exc: | |
logger.error('Reading json file failiure: {}'.format(exc)) | |
return json_structure | |
def save_json_to_file(file_path, json_structure): | |
"""Serializes and writes a json structure to a file.""" | |
if json_structure is None: | |
json_structure = {} | |
try: | |
data = json.dumps( | |
json_structure, indent=4, sort_keys=True, ensure_ascii=False | |
).encode('utf-8') # Force encode. | |
except Exception as exc: | |
logger.error("Json to string failed: {}, {}".format( | |
file_path, exc | |
)) | |
try: | |
with open(file_path, "w+") as handle: | |
handle.write(data) | |
except IOError as exc: | |
logger.error("Could not write file: {}, {}".format(file_path, exc)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment