• 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 JSON to INI Format in Python

Convert JSON to INI Format in Python

Author: Aditya Raj
Last Updated: April 13, 2023

We use JSON files for data transfer and storage. On the other hand, the INI file format is used to store configuration files. This article discusses how to convert a json string or file to INI format in Python. 

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

What is the JSON File Format?

JSON stands for JavaScript Object Notation. It is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. JSON is based on a subset of the JavaScript programming language and uses key-value pairs to represent data.

A JSON file consists of key-value pairs enclosed in curly braces ({}) and separated by commas. The keys are always strings, while the values can be strings, numbers, boolean values, arrays, or other JSON objects.

To understand this, consider the following JSON data.

{
  "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 JSON object contains the data of an employee.

  • The top-level JSON object contains three key-value pairs. The first key is "employee", and the associated value is a JSON object that contains two keys: "name" and "age". The value of the "name" key is the string "John Doe", while the value of the "age" key is the string "35".
  • The second key is "job". The JSON object associated with the "job" key as its value contains three keys: "title", "department", and "years_of_experience". The value of the "title" key is the string "Software Engineer", the value of the "department" key is the string "IT", and the value of the "years_of_experience" key is the string "10".
  • The JSON object has "address" as its third key. The value associated with the "address" key is a JSON object that contains four keys: "street", "city", "state", and "zip". The value of the "street" key is the string "123 Main St.", the value of the "city" key is the string "San Francisco", the value of the "state" key is the string "CA", and the value of the "zip" key is the string "94102".

What is the INI File Format?

INI file format is a simple configuration file format that we use for storing configuration settings for software applications. INI stands for “initialization”, which reflects its original purpose of initializing Windows applications.

An INI file consists of sections and properties. Sections are enclosed in square brackets ([]). Each section contains a set of properties. Properties are key-value pairs separated by an equal sign (=). 

For example, the data shown in the previous JSON file can be represented in the INI 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

Here, the INI file contains the sections "employee", "job", and "address". This is why these literals are contained in square brackets. Each inner key-value pair of the JSON object has been converted into key-value pairs in the INI file.

Now, we will discuss converting a JSON string or file to an INI file in Python.

JSON String to INI File in Python

To convert a json string to an ini file in Python, we will use the json module and the configparser module. For this task, we will use the following steps.

  • First, we will open an empty ini file in write mode using the open() function to store the output ini file. The open() function takes the filename as its first input argument and the Python literal “w” as its second input argument. After execution, it returns a file pointer.
  • Next, we will load the json string into a Python dictionary using the loads() method defined in the json module. The loads() method takes the json string as its input argument and returns the corresponding dictionary. 
  • Now, we will read the data from the Python dictionary to INI format. For this, we will first create a ConfigParser object using the ConfigParser() function defined in the configparser module. 
  • Then, we will load the data from the dictionary to the ConfigParser object using the sections(), add_section(), and set() methods. You can read more about how to convert a dictionary to INI format in this article on converting a Python dictionary to INI format in Python.
  • After loading the data from the dictionary to the ConfigParser object, we will use the write() method to save the ini file to the disk. The write() method, when invoked on a ConfigParser object, takes the file pointer to the INI file as its input and writes the data to the INI file.
  • Finally, we will close the INI file using the close() method.

After executing the above steps, we can easily convert the json string to an ini file in Python. You can observe this in the following example.

import json
import configparser
json_string='{"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"}}'
file =open("employee.ini","w")
python_dict=json.loads(json_string)
config_object = configparser.ConfigParser()
sections=python_dict.keys()
for section in sections:
    config_object.add_section(section)
for section in sections:
    inner_dict=python_dict[section]
    fields=inner_dict.keys()
    for field in fields:
        value=inner_dict[field]
        config_object.set(section, field, str(value))
config_object.write(file)
file.close()

Output INI file.

Output INI File
Output INI File

The above code is somewhat inefficient. You can implement the same logic using an efficient approach as shown below.

import json
import configparser
json_string='{"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"}}'
file =open("employee.ini","w")
python_dict=json.loads(json_string)
config_object = configparser.ConfigParser()
for section, options in python_dict.items():
    config_object.add_section(section)
    for key, value in options.items():
        config_object.set(section, key, str(value))
config_object.write(file)
file.close()

Convert JSON File to INI File in Python

Instead of a json string, we can convert a json file to an ini file in Python. For this, we will open the json file in read mode using the open() function. Then, we will use the load() method defined in the json module to read the data from the json file into a Python dictionary.

The load() method takes the file pointer to the json file as its input argument and returns a Python dictionary after execution. Once we get the dictionary, we can convert it into an INI file as discussed in the previous section. 

Suppose that we have the following JSON file.

Input JSON File
Input JSON File

We can convert this json file into an INI file using the load() method defined in the json module as shown below.

import json
import configparser
file =open("employee.ini","w")
json_file=open("employee.json","r")
python_dict=json.load(json_file)
config_object = configparser.ConfigParser()
for section, options in python_dict.items():
    config_object.add_section(section)
    for key, value in options.items():
        config_object.set(section, key, str(value))
config_object.write(file)
file.close()

The output file looks as follows.

Output INI File
Output INI File

Conclusion

In this article, we discussed how to convert a json string or file to an ini file in Python. To load more about file conversions, you can read this article on how to convert an INI file to a JSON file in Python. You might also like this article on how to convert ini to yaml format 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