JSON

Python - A Quick Start for existing Programers

1 min read

Published Sep 16 2025, updated Sep 30 2025


21
0
0
0

Python

Python has a built in module called json for handling the conversion of json to Python objects and serialising Python objects to json.

It can be imported by:

import json



Converting between JSON and Python

There are the following methods:

  • Serialise (Python → JSON string):
    • json.dumps(obj) → Python object → JSON string
    • json.dump(obj, file) → write JSON directly to a file
  • Deserialise (JSON string → Python):
    • json.loads(json_string) → JSON string → Python object
    • json.load(file) → read JSON directly from a file

JSON ↔ Python type mappings:

JSON

Python

Object {}

dict

Array []

list

String "a"

str

Number

int/float

true/false

True/False

null

None


Formatting options

  • indent=4 → pretty-print JSON with indentation
  • sort_keys=True → sort dictionary keys in output
  • separators=(',', ': ') → control formatting


Examples:

import json

# ----------------------------------------
# Python object
data = {
    "name": "Alice",
    "age": 30,
    "is_admin": True,
    "skills": ["Python", "Django", "Flask"],
    "projects": None
}

# ----------------------------------------
# Python -> JSON string
json_string = json.dumps(data)
print("JSON string:", json_string)

# Pretty print JSON
pretty_json = json.dumps(data, indent=4, sort_keys=True)
print("Pretty JSON:\n", pretty_json)

# Write JSON to file
with open("data.json", "w") as f:
    json.dump(data, f, indent=2)

# ----------------------------------------
# JSON string -> Python
parsed = json.loads(json_string)
print("Parsed back to Python:", parsed)
print("Name:", parsed["name"])

# Read JSON from file
with open("data.json", "r") as f:
    from_file = json.load(f)
    print("From file:", from_file)

# ----------------------------------------
# Controlling separators (compact JSON)
compact_json = json.dumps(data, separators=(',', ':'))
print("Compact JSON:", compact_json)
© 2025 SimpleSteps.guide
AboutFAQPoliciesContact