JSON

Python - A Quick Start for existing Programers

1 min read

Published Sep 16 2025, updated Aug 17 2026


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 objectdata = {    "name": "Alice",    "age": 30,    "is_admin": True,    "skills": ["Python", "Django", "Flask"],    "projects": None}​# ----------------------------------------# Python -> JSON stringjson_string = json.dumps(data)print("JSON string:", json_string)​# Pretty print JSONpretty_json = json.dumps(data, indent=4, sort_keys=True)print("Pretty JSON:\n", pretty_json)​# Write JSON to filewith open("data.json", "w") as f:    json.dump(data, f, indent=2)​# ----------------------------------------# JSON string -> Pythonparsed = json.loads(json_string)print("Parsed back to Python:", parsed)print("Name:", parsed["name"])​# Read JSON from filewith 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