Python Tutorial / Convert and Save JSON Data

JSON is a text format for structured objects, arrays, strings and numbers. json.load and dump work with files; loads and dumps work with strings, and JSON does not preserve every possible Python object or type.

Map JSON values to Python data

JSON Python
object dict
array list
string str
true / false / null True / False / None

JSON keys and strings use double quotes. Python-style single quotes and comments are not arbitrary JSON extensions. A tuple may return as a list after a round trip; dates and Decimal objects need an explicit conversion policy.

For the relevant APIs and platform requirements, see Python: json.

Save a Unicode record and read it back

The English example uses café as a non-ASCII name to make Unicode representation visible. It replaces expenses-demo.json in the practice folder.

Save the complete code below as json_demo.py in a separate practice folder, using UTF-8. Run python json_demo.py in a terminal with your project virtual environment selected. Outside a virtual environment on macOS or Ubuntu, use python3 when that is your interpreter command.

import json
from pathlib import Path

data = {"currency": "KRW", "expenses": [{"name": "café", "amount": 8000}]}
path = Path("expenses-demo.json")
path.write_text(json.dumps(data, ensure_ascii=False, indent=2, allow_nan=False), encoding="utf-8")
loaded = json.loads(path.read_text(encoding="utf-8"))
amount = loaded["expenses"][0]["amount"]
if type(amount) is not int or amount < 0:
    raise ValueError("invalid amount")
print(loaded["expenses"][0]["name"])
print(amount)

Expected output:

café
8000

Distinguish parsing from validation

Successful parsing does not establish that required keys, collection shapes, field types and ranges meet the application’s rules. The sample checks type(amount) is int to exclude bool, an int subclass. isinstance can be appropriate when subclasses should be allowed; choose according to the contract.

Python’s JSON support accepts some nonstandard numeric constants by default. allow_nan=False rejects them during serialization. Strict external-input handling also requires a deliberate policy for such constants and duplicate object keys.

load and dump operate on file-like objects; loads and dumps operate on text strings. dumps returns JSON text rather than creating a file. Write that text or use dump to persist it. Successful JSON parsing does not validate required business fields or amount rules.

Item Behavior
load(file) file → object
loads(text) str → object
dump(obj, file) object → file
dumps(obj) object → str

Separate character representation from encoding

ensure_ascii=False keeps non-ASCII characters readable instead of emitting escape sequences. It does not choose the file encoding; UTF-8 is specified separately. indent changes presentation rather than data meaning.

Malformed JSON raises JSONDecodeError. Correct the quoting or trailing comma instead of switching to eval. Try amount values -1 and true and verify that business validation rejects them, then restore 8000. The example validates one known record shape; a general importer must also validate the surrounding keys and array structure.

The HTTP and JSON lesson applies the same distinction to data received from a server.