• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Convert INI Files to JSON Format in Python

Convert INI Files to JSON Format in Python

Author: Aditya Raj
Last Updated: April 10, 2023

We use the INI file format to store configuration files. On the other hand, JSON files are normally used for data transfer between two software systems. This article discusses how to convert an INI file to a JSON string or file in Python.

Table of Contents
  1. What is the INI file format?
  2. What is the JSON File format?
  3. Convert INI File to JSON String
  4. Convert INI File to JSON File in Python
  5. Conclusion

What is the INI file format?

INI file format is a simple text format for storing configuration data in a plain-text file.

In an INI file, each section is enclosed in square brackets. All the sections contain one or more key-value pairs. The key-value pairs are separated by an equal sign (=), with the key on the left and the value on the right. The key is a string that identifies the setting, while the value can be any valid string or number.

The INI file format is human-readable and easy to parse. This makes it a popular choice for storing and managing application settings, preferences, and other configuration data.

To understand the structure of an INI file, consider the following example file.

[employee]
name=John Doe
age=35

[job]
title=Software Engineer
department=IT
years_of_experience=10

[address]
street=123 Main St.
city=San Francisco
state=CA
zip=94102

The above INI file contains information about an employee’s name, age, job title, department, years of experience, and address. Here, we have divided the information into three sections namely "employee", "job", and "address". You can observe that we have denoted the sections by section headers in square brackets.

  • The "employee" section contains two key-value pairs i.e. "name", and "age".
  • In the "job" section, we have defined three key-value pairs to store the "title", "department", and "years_of_experience" of the employee.
  • The "address" section contains four key-value pairs i.e "street", "city", "state", and "zip" to describe the address of the employee.

Each INI file follows the format described above. You can define configuration settings using sections and key-value pairs for any software system.

What is the JSON File format?

JSON (JavaScript Object Notation) is a lightweight data interchange format. It is a text-based format and we often use it to transmit data between software applications.

The JSON format is also composed of key-value pairs. Here, the key is always a string and the value can be any JSON type, including string, number, boolean, null, array, or another JSON object. We enclose JSON objects in curly braces {} and individual key-value pairs by commas. Structurally, a JSON object looks similar to a Python dictionary.

We can represent the data shown in the previous example using JSON file format as shown below.

{
  "employee": {
    "name": "John Doe",
    "age": "35"
  },
  "job": {
    "title": "Software Engineer",
    "department": "IT",
    "years_of_experience": "10"
  },
  "address": {
    "street": "123 Main St.",
    "city": "San Francisco",
    "state": "CA",
    "zip": "94102"
  }
}

Now, let us discuss how to convert an INI file to a JSON string or file in Python.

Convert INI File to JSON String

To convert an INI file to a JSON string, we will use the json module and the configparser module in Python. Suppose that we have the following INI file.

Input JSON File
Input JSON File

To convert this INI file to a JSON string, we will use the following steps.

  • First, we will create an empty ConfigParser object using the ConfigParser() function defined in the configparser module. We will use this object to read the INI file. 
  • Next, we will open the INI file in read mode using the open() function. The open() function takes the filename as its first input argument and the Python literal “r” as its second input argument. After execution, it returns a file pointer. 
  • Now, we will read the ini file into the ConfigParser object using the read_file() method. The read_file() method, when invoked on a ConfigParser object, takes the file pointer to the ini file as its input argument and loads the data into the ConfigParser object. 
  • Once we get the ConfigParser object with data, we will convert the data into a Python dictionary. For this, we will use the sections() method and the items() method defined in the configparser module.
  • The sections() method, when invoked on a ConfigParser object, returns a list containing all the section names in the ConfigParser object. The items() method, when invoked on the ConfigParser object takes a section name as its input argument. After execution, it returns all the key-value pairs in the particular section as a list of tuples. 
  • To convert the ConfigParser object to a Python dictionary, we will first create an empty dictionary. Then, we will get all the section names in the ConfigParser object using the sections() method. 
  • After this, we iterate through the section names and collect the key-value pairs in the particular section using the items() method as a list of tuples. Here, we will also convert the list of tuples into a Python dictionary using the dict() function. Finally, we will add the section name as a key and the dictionary containing key-value pairs as its associated value into the dictionary that we created before obtaining the section names.
  • After executing the previous step, we will get the contents of the ini file in a Python dictionary. Next, we will convert the dictionary to a json object using the dumps() method defined in the json module. The dumps() method takes the Python dictionary as its input argument and returns a JSON string containing the data from the dictionary.

You can observe all the steps in the following example.

import configparser
import json
config_object = configparser.ConfigParser()
file =open("employee.ini","r")
config_object.read_file(file)
output_dict=dict()
sections=config_object.sections()
for section in sections:
    items=config_object.items(section)
    output_dict[section]=dict(items)

json_string=json.dumps(output_dict)
print("The output JSON string is:")
print(json_string)
file.close()

Output:

The output JSON string is:
{"employee": {"name": "John Doe", "age": "35"}, "job": {"title": "Software Engineer", "department": "IT", "years_of_experience": "10"}, "address": {"street": "123 Main St.", "city": "San Francisco", "state": "CA", "zip": "94102"}}

In the above output, you can observe that we have converted the INI file to a JSON string.

Convert INI File to JSON File in Python

We can also convert an INI file to a JSON file instead of a string. For this, we will use the dump() method instead of the dumps() method after creating the dictionary from the ConfigParser object. 

  • To convert an INI file to a JSON file, we will first convert the ini file to a Python dictionary as shown in the previous example.
  • Then, we will open a JSON file in write mode using the open() function. After execution, the open() function will return a file pointer. 
  • Next, we will use the dump() method to write the data into the json file. The dump() method takes the Python dictionary as its first argument and a file pointer to the json file as its second input argument. After executing, it writes the json object into the file.
  • Finally, we will close the json file using the close() method.

After executing these steps, you can easily convert an INI file to a JSON file in Python. You can observe this in the following example.

import configparser
import json
config_object = configparser.ConfigParser()
file =open("employee.ini","r")
config_object.read_file(file)
output_dict=dict()
sections=config_object.sections()
for section in sections:
    items=config_object.items(section)
    output_dict[section]=dict(items)

json_file =open("employee.json","w")
json.dump(output_dict,json_file)
json_file.close()
file.close()

The output JSON file looks as follows.

Output JSON File
Output JSON File

Conclusion

In this article, we discussed how to convert an INI file to JSON format in Python. To learn more about file conversions, you can read this article on how to convert XML to INI format in Python. You might also like this article on custom JSON decoders in Python.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us