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.
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.
To convert this INI file to a JSON string, we will use the following steps.
- First, we will create an empty
ConfigParser
object using theConfigParser()
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. Theopen()
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 theread_file()
method. Theread_file()
method, when invoked on aConfigParser
object, takes the file pointer to the ini file as its input argument and loads the data into theConfigParser
object. - Once we get the
ConfigParser
object with data, we will convert the data into a Python dictionary. For this, we will use thesections()
method and theitems()
method defined in the configparser module. - The
sections()
method, when invoked on aConfigParser
object, returns a list containing all the section names in theConfigParser
object. Theitems()
method, when invoked on theConfigParser
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 theConfigParser
object using thesections()
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 thedict()
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. Thedumps()
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, theopen()
function will return a file pointer. - Next, we will use the
dump()
method to write the data into the json file. Thedump()
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.
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!
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.