How To Convert Python Dictionary To JSON? (original) (raw)

Last Updated : 12 Jul, 2025

In Python, a dictionary stores information using key-value pairs. But if we want to save this data to a file, share it with others, or send it over the internet then we need to convert it into a format that computers can easily understand. JSON (JavaScript Object Notation) is a simple format used for this. **For example, if we have a dictionary d = {"name": "Tom", "age": 10, "city": "Paris"}, converting it to JSON will represent the data as {"name": "Tom", "age": 10, "city": "Paris"}. Although both look the same, if we check the type of the JSON data, it will be a string, not a dictionary.

Using json.dumps()

json.dumps() converts a dictionary into a JSON-formatted string. It allows various formatting options like indentation, sorting keys and ensuring ASCII encoding, making it useful for debugging and human-readable outputs.

Python `

import json

d = {"name": "shakshi", "age": 21}

print(json.dumps(d, indent=4)) # Pretty print JSON print(json.dumps(d, sort_keys=True)) # Sorted keys print(json.dumps(d, ensure_ascii=False)) # Non-ASCII encoding print(json.dumps([{k: d[k]} for k in d])) # Convert to JSON array format

`

Output

{ "name": "shakshi", "age": 21 } {"age": 21, "name": "shakshi"} {"name": "shakshi", "age": 21} [{"name": "shakshi"}, {"age": 21}]

**Explanation:

**Note: For more information, refer to Read, Write, and Parse JSON using Python

Table of Content

Using json.dump()

json.dump() writes a dictionary directly into a file in JSON format. It avoids the need to manually open and write the JSON string to a file. Additional options like indentation and key sorting can be applied to make the output more structured. This method is best suited for persisting JSON data to a file.

Python `

import json

d = {"name": "Shakshi", "age": 21}

files = [ ("sample_default.json", {}), ("sample_pretty.json", {"indent": 4}), ("sample_sorted.json", {"sort_keys": True, "indent": 4}), ("sample_ascii.json", {"ensure_ascii": False, "indent": 4}), ]

for filename, options in files: with open(filename, "w") as f: json.dump(d, f, **options)

Print JSON representations for reference

for _, options in files: print(json.dumps(d, **options))

`

Output

{"name": "Shakshi", "age": 21} { "name": "Shakshi", "age": 21 } { "age": 21, "name": "Shakshi" } { "name": "Shakshi", "age": 21 }

**Explanation:

Converting nested dictionary to json

Dictionaries can have **nested structures and json.dumps() effectively handles such cases. With indentation, nested objects remain easy to read, ensuring clarity in complex data structures. Encoding and sorting keys can also be applied to nested dictionaries, preserving the hierarchical structure.

Python `

import json

d = {"name": "shakshi", "age": 21, "address": {"city": "Delhi"}}

print(json.dumps(d, indent=4)) # Pretty print JSON print(json.dumps(d, sort_keys=True, indent=4)) # Sorted keys print(json.dumps(d, ensure_ascii=False, indent=4)) # Non-ASCII encoding print(json.dumps([{k: d[k]} for k in d], indent=4)) # Convert to JSON array format

`

**Output

<class 'str'> {
"name": "shakshi",
"age": 21,
"address": {
"city": "Delhi"
}
}
{
"address": {
"city": "Delhi"
},
"age": 21,
"name": "shakshi"
}
{
"name": "shakshi",
"age": 21,
"address": {
"city": "Delhi"
}
}
[
{
"name": "shakshi"
},
{
"age": 21
},
{
"address": {
"city": "Delhi"
}
}
]

**Explanation:

Difference Between Dictionary and JSON

S.No. JSON Dictionary
1. JSON (JavaScript Object Notation) is a data interchange format used to store and exchange data between systems. A dictionary in Python is a built-in data structure used to store a collection of key-value pairs.
2. JSON keys must be strings and enclosed in double quotes. Dictionary keys can be of various data types, including strings, numbers, and tuples (immutable types).
3. JSON has a strict syntax with key-value pairs separated by colons (:), and pairs separated by commas (,). Curly braces {} enclose JSON objects. Python dictionaries use curly braces {} to enclose key-value pairs, with colons : separating keys and values.
4. JSON keys and string values must be enclosed in double quotes (e.g., "key": "value"). In Python dictionaries, keys can be specified without quotes (e.g., key: "value"), although quotes are also allowed.
5. Eg. {"name": "Ram", "age": 30} Eg. {"name": "Shyam", "age": 30}
6. JSON values are accessed using keys as strings (e.g., data["name"]). Dictionary values are accessed using keys (e.g., data["name"]) or using the get() method.
7. JSON data can be saved to and loaded from files using functions like json.dump() and json.load(). Python dictionaries can also be serialized to files using various methods, but you need to handle the serialization/deserialization logic yourself.