pass json file as command line argument through parser , is this possible?
Question: I need to overwrite json file parameters to a python dictionary through
command line argument parser. Since, json file is located in the current
working directory but its name can be dynamic , so i want something like below
:-

> python python_script --infile json_file

# python_script:

    
    
    if __name__ == "__main__":
       profileInfo = dict()
       profileInfo['profile'] = "enterprisemixed"
       profileInfo['nodesPerLan'] = 50
    

# json_file:

    
    
    {
       "profile":"adhoc",               
       "nodesPerLan" : 4
    }
    

I tried to add the following lines, but don't know how to load this json data
to the python dictionary :-

    
    
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--infile', nargs = 1, help="JSON file to be processed",type=argparse.FileType('r'))
    arguments = parser.parse_args()
    


Answer: Read the JSON file with the name given to `--infile` and update your
`profileInfo`:

    
    
    import json
    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument('--infile', nargs=1,
                        help="JSON file to be processed",
                        type=argparse.FileType('r'))
    arguments = parser.parse_args()
    
    # Loading a JSON object returns a dict.
    d = json.load(arguments.infile[0])
    
    profileInfo = {}
    profileInfo['profile'] = "enterprisemixed"
    profileInfo['nodesPerLan'] = 50
    
    print(profileInfo)
    # Overwrite the profileInfo dict
    profileInfo.update(d)
    print(profileInfo)
    

