The following table shows how Python data types are converted to their JSON equivalents during serialization and deserialization:
remember this table.
This repository contains small examples demonstrating how to work with JSON in Python:
json_and_pythonObj.py: How to serialize (encode) Python built-in types to JSON and deserialize (decode) JSON into Python built-ins usingjson.dumps,json.dump,json.loads, andjson.load.json_and_customObj.py: How to serialize custom Python objects by providing adefaultfunction or by subclassingjson.JSONEncoder, and how to decode JSON back into custom objects usingobject_hook.example_json_format.json: A sample JSON file showing a nested object with arrays and booleans.person.json: A sample JSON file used byjson_and_pythonObj.py.
-
Serialization (Encoding)
- Converting Python objects to JSON format.
- Use
json.dumps(obj)to get a JSON string. - Use
json.dump(obj, file)to write JSON directly to a file. - Both functions accept formatting parameters like
indent=4for pretty printing.
-
Deserialization (Decoding)
- Converting JSON strings/files back into Python objects.
- Use
json.loads(json_string)to parse a JSON string into Python built-ins (usuallydict,list,str,int,float,bool,None). - Use
json.load(file)to parse JSON from a file.
-
Built-in types vs custom objects
- The
jsonmodule can serialize built in Python types directly (dicts, lists, strings, numbers, booleans, None). - Custom classes (instances of user-defined classes) are not serializable by default. Attempting to
json.dumps()them raises aTypeError.
- The
-
Making custom objects serializable
-
Option A: Provide a
defaultcallable tojson.dumpsthat returns a JSON serializable representation (eg. a dict). -
Option B: Subclass
json.JSONEncoderand overridedefault(self, obj)to return a serializable representation.
-
-
Decoding custom objects
json.loads(..., object_hook=...)accepts a callable that transforms dicts into custom objects. If theobject_hookreturns an instance, that instance will replace the dict.
-
Pitfall: shadowing the standard library
-
One thing I ran into while writing these examples: if you name a script after a standard library module (for example
json.py,os.py,sys.py,requests.py), Python will import your local file first and shadow the real module. That can lead to confusing errors likeAttributeError: module 'json' has no attribute 'dumps',RecursionError, or other import failures, I hit this while developing the examples, so watch out for it. -
How to fix
- Don’t name your script
json.py(or any other stdlib/module name). Use something likejson_example.pyinstead. - Remove cached bytecode: delete the
__pycache__folder and any*.pycfiles. - Restart your Python interpreter or editor/IDE so the old module is not still loaded.
- Check the current working directory for accidentally named files, Python resolves imports from there first.
- Don’t name your script
-
Open a terminal (PowerShell on Windows) in the repository root (c:\JSON_in_python).
Run examples:
python .\json_and_pythonObj.py
python .\json_and_customObj.pyExpected behavior:
json_and_pythonObj.pyprints a pretty JSON string forpersonand writes/readsperson.json.json_and_customObj.pyprints the JSON representation of aPersoninstance and shows decoding back into aPersonobject usingobject_hook.
This is my example code for learning purposes. Use freely.