Using JSON config files in Python.

Do you want to load config values at run time in Python? After reading this tutorial you have learned how to create a JSON configuration file, load it with Python and how to access values from it.

Let’s assume your app needs variables width and height and you want your users to be able to change the values in a config file.

Step 1: Create JSON config file

"width" : 1024,
"height" : 768

Step 2: Create Python script

To open config.JSON, you can use Pythons open function. To use the json load function, you need to import the json module. json.load returns a dictionary that can be accessed by its keys. The syntax is data['width'].

Here is the code:

import json

with open('config.json') as config_file:
data = json.load(config_file)

width = data['width']
height = data['height']


Open a terminal and execute the script with python3 The result should look like this:

Written by Loek van den Ouweland on 2018-09-11. Questions regarding this artice? You can send them to the address below.