Saturday, September 1, 2018

Python:: Simple Module to Maintain JSON Content

Recently I had a requirement to maintain details in a file dynamically and retrieve the data as on needed. I chosen to maintain data in JSON file and created following Python class module to manage it efficiently.

Class Module:

#!/usr/bin/env python
import os
import json

class jsondb(object):

    def __init__(self, location):
        self.load(location)

    def load(self, location):
        '''Loads JSON file content.'''
        location = os.path.expanduser(location)
        self.location = location
        if os.path.exists(location):
            self._loadjson()
        else:
            self.json = {}
        return True

    def set(self, key, value):
        '''Set the value of a key'''
        self.json[key] = value
        self._dumpjson()
        return True

    def get(self, key):
        '''Get the value of a key'''
        try:
            return self.json[key]
        except KeyError:
            return None

    def remove(self, key):
        '''Delete a key'''
        del self.json[key]
        self._dumpjson()
        return True

    def getall(self):
        '''Return a list of all keys in JSON file'''
        return self.json.keys()

    def _loadjson(self):
        '''Load the JSON info from the file'''
        self.json = json.load(open(self.location, 'rb'))

    def _dumpjson(self):
        '''Save the JSON dump into the file'''
        json.dump(self.json, open(self.location, 'wt'),sort_keys=True, indent=4)


Usage:

#Import module
from jsonModule import jsondb

#Load JSON Repository
jsondb= jsondb("sample.json");

#Set Value
jsondb.set('key', 'value')

#Get Value
jsondb.get('key')

#Get All Keys
jsondb.getall()

#Remove Key
jsondb.remove('key')