Python’s standard library includes the json module, allowing developers to parse API text, read .json files and serialize objects without installing a separate package. The similarly named methods json.load, json.loads, json.dump and json.dumps have different inputs and outputs.
\n

\n
Quick takeaway: This guide explains python json through real-world examples, frequent errors and ways to verify your work. Use sample records rather than private client data when trying online tools.
json.loads and json.dumps operate on strings
The final letter s can help you remember the difference. json.loads parses a JSON string into a Python object; json.dumps converts an eligible Python object into a JSON string. Quoting, types and nested structures must still follow JSON rules. Use these functions when the data is already in memory.
import json
raw = '{"name":"Ella","score":93}'
data = json.loads(raw)
print(data["name"])
print(json.dumps(data, indent=2))
A JSON object commonly becomes a dict and a JSON array becomes a list. true maps to True and null to None in Python. These are language mappings, not changes to the JSON text specification.
Read a JSON file with json.load
Use the built-in open function and a with block to close the file automatically. The load function accepts an open file-like object rather than a file path string. Specify encoding=”utf-8″ for predictable text handling across operating systems.
import json
with open("settings.json", "r", encoding="utf-8") as file:
settings = json.load(file)
print(settings.get("theme", "default"))
A missing property and a missing file are different failure cases. Use .get when the field is optional; validate required keys when the application depends on them.
Write formatted JSON using json.dump
The dump function writes to a file-like object. An indent argument adds whitespace for human inspection. For Chinese names, accented words or other Unicode text, ensure_ascii=False keeps characters readable and write using UTF-8.
import json
person = {"name": "Chloé", "city": "Montréal", "active": True}
with open("person.json", "w", encoding="utf-8") as f:
json.dump(person, f, ensure_ascii=False, indent=2)
Remember that writing with mode w replaces the previous file. Back up important configuration and do not store private access tokens in public files.
Handle malformed JSON carefully
Catch json.JSONDecodeError when the document is syntactically invalid. It reports a line and column that can guide debugging. Separately handle OSError for missing files or permission problems. In a production service, do not display sensitive file paths or raw customer data to end users.
import json
try:
with open("settings.json", encoding="utf-8") as f:
data = json.load(f)
except json.JSONDecodeError as error:
print(f"Invalid JSON at line {error.lineno}")
except OSError:
print("Unable to read file")
A successful parse does not guarantee the expected type. If your code expects a dictionary, check it before accessing data[“items”].
Practical task-list example
Create a list of dictionaries representing tasks, save it to disk and load it back. This small exercise uses objects, arrays, booleans and file I/O together. It can be adapted into a command-line study project or test fixture.
import json
tasks = [{"title":"Review JSON","done":False},{"title":"Ship report","done":True}]
with open("tasks.json","w",encoding="utf-8") as f:
json.dump(tasks,f,indent=2)
with open("tasks.json",encoding="utf-8") as f:
loaded=json.load(f)
print([t["title"] for t in loaded if not t["done"]])
Custom Python dates, Decimal objects and other specialized values often need explicit conversion before JSON serialization. Avoid uncontrolled float conversions for financial records.
Frequently asked questions
Is JSON included with Python? Yes, in the json module. What does the s mean? loads and dumps work with strings. Is JSON equal to a dict? No, one is a textual format and the other an in-memory Python type. Does json.dump append records? It writes a serialized document; repeated dumps are not a valid way to create a single standard JSON file. Can I read an API response? Yes, but validate its shape and follow the HTTP library’s API.
Practical checklist before using this in production
- Confirm that the source, file extension, expected type and encoding match your data contract.
- Test a typical valid example and at least one deliberately invalid example.
- Check empty values, missing fields, Unicode input and unusual numbers rather than relying only on the easiest sample.
- Keep secrets and personal data out of public web-based tools unless your organization has approved the handling.
- Document version, timezone and currency assumptions for projects in the USA, UK, Canada, Australia or China where they are relevant.
These practices make the examples easier to adapt internationally without assuming that a local service is available in every region.
Relevant free tools on Perkability Rewards
Try the directly linked utilities, not a new landing page. The site also has an existing JSON errors guide and a JSON arrays tutorial.
- JSON Formatter: practise using non-sensitive sample data relevant to this topic.
- Base64 Encoder & Decoder: practise using non-sensitive sample data relevant to this topic.
Authoritative technical references:
Disclosure: This educational article includes a third-party Adsterra 160×600 banner and social bar. Their display depends on the visitor’s browser and advertising-network settings. The article does not make promises about Google ranking or location-specific availability.
ADVERTISEMENT · SPONSORED LINK
Support PerkAbility Rewards
Enjoy our free resources? You can optionally visit an advertising partner. The destination is a third-party advertisement and may vary.
Visit sponsored offer ↗Optional external advertisement. Your access to this article does not depend on clicking.

One Response