How to Convert Dictionary to JSON in Python

Here are two ways to convert a dictionary to json in Python:

  1. Using json.dumps() Method
  2. Using  json.dump() Method

Method 1: Using json.dumps() Method

The json.dumps() method takes a dictionary as input and converts it into a JSON-formatted string.

Example 1: Basic Conversion

Visual Representation of Python Convert Dictionary to JSON using json.dumps() method

import json

# Define a dictionary with application details
app_dict = {
 'name': 'messenger',
 'playstore': True,
 'company': 'Meta',
 'price': 100
}

# Print the original dictionary and its type
print(app_dict)
print(type(app_dict)) 

# Convert the dictionary to a JSON string using json.dumps()
app_json = json.dumps(app_dict)

# Print the resulting JSON string and its type
print(app_json) 
print(type(app_json)) 

Output

{'name': 'messenger', 'playstore': True, 'company': 'Meta', 'price': 100}
<class 'dict'>
{"name": "messenger", "playstore": true, "company": "Meta", "price": 100}
<class 'str'>

Example 2 : Using Nested Dictionary

import json

# Define a nested dictionary with application details

nested_app_dict = {
   'app_info': {
     'name': 'messenger',
     'playstore': True
 },
   'company_info': {
     'company_name': 'Meta',
     'price': 100
 }
}

print(nested_app_dict)
print(type(nested_app_dict)) 

app_json = json.dumps(nested_app_dict, indent = 3)

print(app_json) 
print(type(app_json)) 

Output

{'app_info': {'name': 'messenger', 'playstore': True}, 
'company_info': {'company_name': 'Meta', 'price': 100}}
<class 'dict'>
{
  "app_info": {
    "name": "messenger",
    "playstore": true
  },
  "company_info": {
    "company_name": "Meta",
    "price": 100
  }
}
<class 'str'>

The use of indent=3 in the method improves the readability of the JSON output, especially for nested structures.

Example 3 : Sorting Keys

To get the consistent order in the JSON string, you can sort the keys by passing True to the sort_keys parameter.
Visual Representation of Using Sorting Keys
import json

# Define a dictionary with application details
app_dict = {
 'name': 'messenger',
 'playstore': True,
 'company': 'Meta',
 'price': 100
}

# Print the original dictionary and its type
print(app_dict)
print(type(app_dict)) 

app_json = json.dumps(app_dict, sort_keys=True)

# Print the resulting JSON string and its type
print(app_json) 
print(type(app_json)) 

Output

{'name': 'messenger', 'playstore': True, 'company': 'Meta', 'price': 100}
<class 'dict'>
{"company": "Meta", "name": "messenger", "playstore": true, "price": 100}
<class 'str'>

Example 4 : Dict to JSON Array

The list comprehension creates a list, where each element is a dictionary containing one key-value pair from the original dictionary and then dumps() method converts it.

import json

# Define a dictionary with application details
app_dict = {
 'name': 'messenger',
 'playstore': True,
 'company': 'Meta',
 'price': 100
}

# Print the original dictionary and its type
print(app_dict)
print(type(app_dict)) 

arr = [{x: app_dict[x]} for x in app_dict]

app_json_arr = json.dumps(arr, indent=3)

# Print the resulting JSON string and its type
print(app_json_arr) 
print(type(app_json_arr))

Output

{'name': 'messenger', 'playstore': True, 'company': 'Meta', 'price': 100}
<class 'dict'>
[
 {
 "name": "messenger"
 },
 {
 "playstore": true
 },
 {
 "company": "Meta"
 },
 {
 "price": 100
 }
]
<class 'str'>

Method 2: Using json.dump() Method

You use json.dump() to write the dictionary to the file in JSON format.

The with statement ensures the file is properly handled and closed after writing.

Visual Representation of Using json.dump() Method

Example

import json

# Define a dictionary with application details
app_dict = {
 'name': 'messenger',
 'playstore': True,
 'company': 'Meta',
 'price': 100
}

print(app_dict)
print(type(app_dict)) 

# Open a file named 'app.json' in write mode
with open('app.json', 'w') as json_file: 
 # Convert and write the dictionary to a JSON file
 json.dump(app_dict, json_file) 

print("Dictionary has been successfully written to JSON File")

Output

app_json

{'name': 'messenger', 'playstore': True, 'company': 'Meta', 'price': 100}
<class 'dict'>
Dictionary has been successfully written to JSON File

2 thoughts on “How to Convert Dictionary to JSON in Python”

  1. AttributeError Traceback (most recent call last)
    In [34]:
    Line 116: jsonData = json.loads(ms_json)

    AttributeError: ‘bytes’ object has no attribute ‘loads’

    is this a common issue

    Reply
  2. This is a great tutorial on how to convert a dictionary to JSON. I have used this technique before to convert a dictionary of user data into a JSON object.

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.