Wednesday, March 25, 2015

source code of reading json configuration file from command line in python

In many application , we want to read a file as a configuration file from command line . here I have written a source code  to read json configuration file in python


source code:
#!/usr/bin/env python

from optparse import OptionParser
import re
import json
import collections

def utf8(data):
    """Encodes the given text as utf-8.
    Returns a string of bytes.
    """
    if isinstance(data, str):
       
        return data
    elif isinstance(data, unicode):
        
        return data.encode("utf-8")   

    return _modify_children(data, utf8)

def _modify_children(data, operation):
    if isinstance(data, collections.Mapping):
  
        return dict(map(operation, data.iteritems()))
    elif isinstance(data, collections.Iterable):
        
        return type(data)(map(operation, data))
    else:
        
        return data

     


def main():
    parser = OptionParser(usage="usage: %prog [options] filename",
                          version="%prog 1.0")
 
    (options, args) = parser.parse_args()

    if len(args) != 1:
        parser.error("wrong number of arguments")


    with open(args[0]) as f:
      data = re.compile("^\s*//.*$", re.MULTILINE).sub("", f.read())
    

    print "**** DATA  *********"
    print data

    


    valid_data = json.loads(data) 

   
   
    # print valid_data 

    # print valid_data["jobs"][0]
    # print valid_data["jobs"][1]

    new_data = utf8(valid_data)




    print "********* unicode encoded data *********" 

    print new_data





if __name__ == '__main__':
    
    main()
here I have used python library optparse to parse the command line argument in our python code. This library helps to read the configuration file mentioned in command line. the json .loads is used to decode the json data to unicode then is again encoded to the python string. To encode the json file , the utf8 function is created. this utf8 function Encodes the given text as utf-8 and returns a string of bytes.

No comments:

Post a Comment