DEV Community

Dendi Handian
Dendi Handian

Posted on

Simple Python JSON Exporter & Importer

Exporter Function

import json

def export_json(filename, obj):
    with open(filename, 'w') as writer:
        writer.write(json.dumps(obj, indent=2))
Enter fullscreen mode Exit fullscreen mode

Importer Function

import json

def import_json(filename):
    obj = {}
    with open(filename, 'r') as reader:
        obj = reader.read()
    return json.loads(obj)
Enter fullscreen mode Exit fullscreen mode

Export and Import Dictionary (JSON object)

sample_dict = {
    "maps": [
        {'a': 1},
        {'b': 2},
        {'c': 3},
        {'d': 4},
    ]
}

export_json('maps.json', sample_dict)
obj = import_json('maps.json')
print(type(obj))
print(obj)
Enter fullscreen mode Exit fullscreen mode

Export and Import List (List of JSON Objects)

sample_list = [
    {'a': 1},
    {'b': 2},
    {'c': 3},
    {'d': 4},
]

export_json('maps.json', sample_list)
obj = import_json('maps.json')
print(obj)
print(type(obj))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)