Here are two ways to convert a dictionary to json in Python:
- Using json.dumps() Method
- 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
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
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.
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
{'name': 'messenger', 'playstore': True, 'company': 'Meta', 'price': 100}
<class 'dict'>
Dictionary has been successfully written to JSON File
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
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
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.