IAM

OPENSOURCEFAN STUDYING
STUDYINGCOMPUTERSCIENCEANDMATH COMPUTERSCIENCE

Check out the latest superpixel benchmark — Superpixel Benchmark (2016) — and let me know your opinion! @david_stutz
04thMAY2017

SNIPPET

Reading and writing JSON files in Python.

json_io.py
#!/usr/bin/env python
"""
JSON reading/writing.
"""

import os
import json

def read_json(file):
    """
    Read a JSON file.

    :param file: path to file to read
    :type file: str
    :return: parsed JSON as dict
    :rtype: dict
    """

    assert os.path.exists(file), 'file %s not found' % file

    with open(file, 'r') as fp:
        return json.load(fp)

def write_json(file, data):
    """
    Read a JSON file.

    :param file: path to file to read
    :type file: str
    :param data: data to write
    :type data: mixed
    :return: parsed JSON as dict
    :rtype: dict
    """

    with open(file, 'w') as fp:
        json.dump(data, fp)

if __name__ == '__main__':
    config = {
        "test": 1,
        "test2": "test2",
        "test3": [0, 1, 2],
        "test4": {
            "a": 0,
            "b": "b"
        }
    }

    print(config)
    write_json('test.json', config)

    config = read_json('test.json')
    print(config)

What is your opinion on the code snippet? Is it working? Let me know your thoughts in the comments below or using the following platforms: