How to Convert Python Dict to JSON and Back

Convert Python dictionaries to JSON text and back with a simple helper that serializes and deserializes data structures.

Easy Python 3.9+ Aug 9, 2026 Cloud + Python 14 views 0 copies

Python code

35 lines
Python 3.9+
import json
from datetime import datetime, timezone


def convert_data(data, source_format=None, target_format="json"):
    """
    Convert Python data structures to txt/json and back.
    For beginners: shows how to serialize/deserialize.
    """
    if source_format == "json" and target_format == "dict":
        return json.loads(data)
    if source_format == "dict" and target_format == "json":
        return json.dumps(data, indent=2)
    if source_format is None and target_format == "json":
        return json.dumps(data, indent=2)
    raise ValueError("Unsupported conversion")


def add_timestamp():
    """Return current UTC timestamp as ISO string."""
    return datetime.now(timezone.utc).isoformat()


if __name__ == "__main__":
    sample_dict = {
        "name": "PythonBasic",
        "level": 1,
        "topics": ["variables", "functions", "files"],
        "created": add_timestamp()
    }
    json_text = convert_data(sample_dict, "dict", "json")
    print("Converted to JSON:\n", json_text)
    print("\nConverted back to dict:")
    restored = convert_data(json_text, "json", "dict")
    print(restored, type(restored))

Output

stdout
Converted to JSON:
 {
  "name": "PythonBasic",
  "level": 1,
  "topics": [
    "variables",
    "functions",
    "files"
  ],
  "created": "2024-01-15T12:34:56.789012+00:00"
}

Converted back to dict:
{'name': 'PythonBasic', 'level': 1, 'topics': ['variables', 'functions', 'files'], 'created': '2024-01-15T12:34:56.789012+00:00'} <class 'dict'>

How it works

The json.dumps call serializes a Python dict into a JSON string, using indent=2 for readable formatting. json.loads does the reverse — it parses JSON text back into native Python objects like dicts and lists. The helper uses explicit source/target format checks to make conversions predictable and beginner-friendly. The timestamp is generated in UTC with timezone info so the data stays consistent across cloud services that expect ISO 8601 strings. This pattern is the foundation for exchanging data between Python services and REST APIs or storage systems.

Common mistakes

  • Using `json.load` instead of `json.loads` when parsing a JSON string (load reads from a file)
  • Forgetting to import `json` before calling the conversion functions
  • Passing the data in the wrong order to the helper (source vs target format)
  • Assuming all Python types serialize to JSON — tuples become lists and custom objects need a custom encoder

Variations

  1. Use `json.dumps(data)` without indent for compact output when sending to an API
  2. Use `pathlib.Path.read_text` plus `json.loads` to read a JSON file from disk
  3. Add `json.dumps(data, sort_keys=True)` for alphabetically ordered keys

Real-world use cases

  • Serializing a Python dict payload before sending it in a POST request to a cloud API.
  • Deserializing JSON responses from AWS Lambda or Google Cloud Functions into workable Python dicts.
  • Converting job results between JSON files and in-memory dicts in a serverless batch pipeline.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Cloud + Python

Related tutorials and quizzes for this topic.