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:

Grüsse aus Berlin!
This is a cookie free and popup free website.
Join me in making the web enjoyable again by removing the need for annoying cookie warnings and silly newsletter overlays!