How to convert a nested dictionary to json in Python

This tutorial provides you with step-by-step instructions on how to convert a nested dictionary to JSON in Python. Also, it will show you, how to convert a dictionary to JSON in Python.

Convert dictionary to JSON Python

Below is a simple example in Python that demonstrates how to convert a dictionary into a JSON formatted string, and also how to write this JSON data to a file.

import json

# Sample dictionary
data = {
    "name": "Alice",
    "age": 25,
    "is_student": False,
    "courses": ["Math", "Physics"],
    "grades": {
        "Math": 90,
        "Physics": 85
    }
}

# Convert dictionary to JSON string
json_string = json.dumps(data, indent=4)

# Output JSON string to the console
print("JSON String:")
print(json_string)

# Write JSON data to a file
with open('data.json', 'w') as file:
    json.dump(data, file, indent=4)

print("\nThe JSON data has been written to 'data.json'")
  1. We import the json module which is part of Python’s standard library.
  2. We create a sample dictionary called data. This dictionary has different types of data, including nested data (a list and another dictionary).
  3. We use the json.dumps() method to convert the dictionary into a JSON formatted string. The indent parameter is used for pretty-printing.
  4. We print this JSON string to the console.
  5. We use the json.dump() method to write the dictionary to a file in JSON format. We open a file called ‘data.json’ in write mode, and write the JSON data to this file with an indentation of 4 spaces for readability.
  6. Lastly, we print a message indicating that the JSON data has been written to the file.

You can run this script by saving it as a .py file (e.g., convert_to_json_example.py) and executing it using Python from the command line:

python convert_to_json_example.py

Convert nested dictionary to JSON in Python

Now, let us check step by step, how to convert a nested dictionary to JSON in Python.

Follow the below steps:

  • Create a Python File: Create a new Python file (e.g., convert_to_json.py) using a text editor or an Integrated Development Environment (IDE) like PyCharm or Visual Studio Code.
  • Import JSON Module: At the top of your file, import the built-in json module. This module provides methods to encode dictionaries into JSON format and decode JSON into dictionaries.
import json
  • Create a Nested Dictionary: Create a nested dictionary that you want to convert to JSON. A nested dictionary means a dictionary within a dictionary.
my_data = {
    "name": "John",
    "age": 30,
    "city": "New York",
    "languages": {
        "English": "Fluent",
        "Spanish": "Intermediate"
    }
}
  • Convert Dictionary to JSON String: Use the json.dumps() method to convert the dictionary into a JSON formatted string. Optionally, you can use the indent parameter to format the JSON string for better readability.
json_string = json.dumps(my_data, indent=4)
  • Print JSON String: Print the resulting JSON string to the console to verify that the conversion was successful.
print(json_string)

Once you run the above code, you can see the output like below:

{
    "name": "John",
    "age": 30,
    "city": "New York",
    "languages": {
        "English": "Fluent",
        "Spanish": "Intermediate"
    }
}
python nested dictionary to json

This is how to convert a nested dictionary to JSON in Python. Here we saw a step-by-step article.

You may also like: