18.3. JSON File
json.load(file) -> dict
json.dump(data, file) -> None
file extension
.json
18.3.1. SetUp
>>> import json
18.3.2. Write Data to JSON File
json.dump(data, file) -> None
file extension
.json
def dump(obj: Any,
fp: IO[str],
*,
skipkeys: bool = ...,
ensure_ascii: bool = ...,
check_circular: bool = ...,
allow_nan: bool = ...,
cls: type[JSONEncoder] | None = ...,
indent: None | int | str = ...,
separators: tuple[str, str] | None = ...,
default: (Any) -> Any | None = ...,
sort_keys: bool = ...,
**kwds: Any) -> None
SetUp:
>>> DATA = {
... 'firstname': 'Mark',
... 'lastname': 'Watney',
... }
Usage:
>>> with open('/tmp/myfile.json', mode='w') as file:
... json.dump(DATA, file)
Result:
>>> print(open('/tmp/myfile.json').read())
{"firstname": "Mark", "lastname": "Watney"}
18.3.3. Read Data From JSON File
json.load(file) -> dict
file extension
.json
def load(fp: SupportsRead[str | bytes],
*,
cls: type[JSONDecoder] | None = ...,
object_hook: (dict) -> Any | None = ...,
parse_float: (str) -> Any | None = ...,
parse_int: (str) -> Any | None = ...,
parse_constant: (str) -> Any | None = ...,
object_pairs_hook: (list[tuple[Any, Any]]) -> Any | None = ...,
**kwds: Any) -> Any
SetUp:
>>> DATA = """{
... "firstname": "Mark",
... "lastname": "Watney"
... }"""
>>>
>>> _ = open('/tmp/myfile.json', mode='w').write(DATA)
Usage:
>>> with open('/tmp/myfile.json') as file:
... result = json.load(file)
>>>
>>> print(result)
{'firstname': 'Mark', 'lastname': 'Watney'}
18.3.4. Assignments
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% About
# - Name: JSON File Dump
# - Difficulty: easy
# - Lines: 2
# - Minutes: 3
# %% English
# 1. Dump `result` to file `FILE` in JSON format
# 2. Run doctests - all must succeed
# %% Polish
# 1. Zrzuć `result` do pliku `FILE` w formacie JSON
# 2. Uruchom doctesty - wszystkie muszą się powieść
# %% Hints
# - `with open(mode='wt') as file:`
# - `json.dump()`
# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from os import remove
>>> result = open(FILE).read()
>>> remove(FILE)
>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'
>>> assert len(result) > 0, \
'Variable `result` should not be empty'
>>> print(result) # doctest: +NORMALIZE_WHITESPACE
[["sepal_length", "sepal_width", "petal_length", "petal_width", "species"],
[5.8, 2.7, 5.1, 1.9, "virginica"],
[5.1, 3.5, 1.4, 0.2, "setosa"],
[5.7, 2.8, 4.1, 1.3, "versicolor"],
[6.3, 2.9, 5.6, 1.8, "virginica"],
[6.4, 3.2, 4.5, 1.5, "versicolor"],
[4.7, 3.2, 1.3, 0.2, "setosa"],
[7.0, 3.2, 4.7, 1.4, "versicolor"],
[7.6, 3.0, 6.6, 2.1, "virginica"],
[4.9, 3.0, 1.4, 0.2, "setosa"]]
"""
import json
FILE = '_temporary.json'
DATA = [
('sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species'),
(5.8, 2.7, 5.1, 1.9, 'virginica'),
(5.1, 3.5, 1.4, 0.2, 'setosa'),
(5.7, 2.8, 4.1, 1.3, 'versicolor'),
(6.3, 2.9, 5.6, 1.8, 'virginica'),
(6.4, 3.2, 4.5, 1.5, 'versicolor'),
(4.7, 3.2, 1.3, 0.2, 'setosa'),
(7.0, 3.2, 4.7, 1.4, 'versicolor'),
(7.6, 3.0, 6.6, 2.1, 'virginica'),
(4.9, 3.0, 1.4, 0.2, 'setosa'),
]
# Dump `result` to file `FILE` in JSON format
# FIXME: użyto zip, który wprowadzany jest w idioms (następny rozdział)
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% About
# - Name: JSON File Dump
# - Difficulty: easy
# - Lines: 4
# - Minutes: 5
# %% English
# 1. Extract from input a header and rows
# 2. Create `result: list[dict]`:
# - key - name from the header
# - value - measurement or species
# 3. Dump `result` to file `FILE` in JSON format
# 4. Run doctests - all must succeed
# %% Polish
# 1. Z danych wydziel nagłówek i wiersze
# 2. Wygeneruj `result: list[dict]`:
# - klucz - nazwa z nagłówka
# - wartość - wyniki pomiarów lub gatunek
# 3. Zrzuć `result` do pliku `FILE` w formacie JSON
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Hints
# - `with open(mode='wt') as file:`
# - `json.dump()`
# - `dict(zip(header,row))`
# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from os import remove
>>> result = open(FILE).read()
>>> remove(FILE)
>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'
>>> assert len(result) > 0, \
'Variable `result` should not be empty'
>>> print(result) # doctest: +NORMALIZE_WHITESPACE
[{"sepal_length": 5.8, "sepal_width": 2.7, "petal_length": 5.1, "petal_width": 1.9, "species": "virginica"},
{"sepal_length": 5.1, "sepal_width": 3.5, "petal_length": 1.4, "petal_width": 0.2, "species": "setosa"},
{"sepal_length": 5.7, "sepal_width": 2.8, "petal_length": 4.1, "petal_width": 1.3, "species": "versicolor"},
{"sepal_length": 6.3, "sepal_width": 2.9, "petal_length": 5.6, "petal_width": 1.8, "species": "virginica"},
{"sepal_length": 6.4, "sepal_width": 3.2, "petal_length": 4.5, "petal_width": 1.5, "species": "versicolor"},
{"sepal_length": 4.7, "sepal_width": 3.2, "petal_length": 1.3, "petal_width": 0.2, "species": "setosa"},
{"sepal_length": 7.0, "sepal_width": 3.2, "petal_length": 4.7, "petal_width": 1.4, "species": "versicolor"},
{"sepal_length": 7.6, "sepal_width": 3.0, "petal_length": 6.6, "petal_width": 2.1, "species": "virginica"},
{"sepal_length": 4.9, "sepal_width": 3.0, "petal_length": 1.4, "petal_width": 0.2, "species": "setosa"}]
"""
import json
FILE = '_temporary.json'
DATA = [
('sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species'),
(5.8, 2.7, 5.1, 1.9, 'virginica'),
(5.1, 3.5, 1.4, 0.2, 'setosa'),
(5.7, 2.8, 4.1, 1.3, 'versicolor'),
(6.3, 2.9, 5.6, 1.8, 'virginica'),
(6.4, 3.2, 4.5, 1.5, 'versicolor'),
(4.7, 3.2, 1.3, 0.2, 'setosa'),
(7.0, 3.2, 4.7, 1.4, 'versicolor'),
(7.6, 3.0, 6.6, 2.1, 'virginica'),
(4.9, 3.0, 1.4, 0.2, 'setosa'),
]
# Extract from input a header and rows
# Create `result: list[dict]`:
# - key - name from the header
# - value - measurement or species
# Dump `result` to file `FILE` in JSON format
data = ...
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% About
# - Name: JSON File Load
# - Difficulty: easy
# - Lines: 2
# - Minutes: 3
# %% English
# 1. Read JSON data from `FILE`
# 2. Run doctests - all must succeed
# %% Polish
# 1. Odczytaj dane JSON z pliku `FILE`
# 2. Uruchom doctesty - wszystkie muszą się powieść
# %% Hints
# - `with open(mode='rt') as file:`
# - `json.load()`
# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from os import remove
>>> remove(FILE)
>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'
>>> assert len(result) > 0, \
'Variable `result` should not be empty'
>>> assert all(type(row) is dict for row in result), \
'Variable `result` should be a list[dict]'
>>> result # doctest: +NORMALIZE_WHITESPACE
[{'sepal_length': 5.8, 'sepal_width': 2.7, 'petal_length': 5.1, 'petal_width': 1.9, 'species': 'virginica'},
{'sepal_length': 5.1, 'sepal_width': 3.5, 'petal_length': 1.4, 'petal_width': 0.2, 'species': 'setosa'},
{'sepal_length': 5.7, 'sepal_width': 2.8, 'petal_length': 4.1, 'petal_width': 1.3, 'species': 'versicolor'},
{'sepal_length': 6.3, 'sepal_width': 2.9, 'petal_length': 5.6, 'petal_width': 1.8, 'species': 'virginica'},
{'sepal_length': 6.4, 'sepal_width': 3.2, 'petal_length': 4.5, 'petal_width': 1.5, 'species': 'versicolor'},
{'sepal_length': 4.7, 'sepal_width': 3.2, 'petal_length': 1.3, 'petal_width': 0.2, 'species': 'setosa'},
{'sepal_length': 7.0, 'sepal_width': 3.2, 'petal_length': 4.7, 'petal_width': 1.4, 'species': 'versicolor'},
{'sepal_length': 7.6, 'sepal_width': 3.0, 'petal_length': 6.6, 'petal_width': 2.1, 'species': 'virginica'},
{'sepal_length': 4.9, 'sepal_width': 3.0, 'petal_length': 1.4, 'petal_width': 0.2, 'species': 'setosa'}]
"""
import json
FILE = r'_temporary.json'
with open(FILE, mode='wt') as file:
file.write("""[
{"sepal_length": 5.8, "sepal_width": 2.7, "petal_length": 5.1, "petal_width": 1.9, "species": "virginica"},
{"sepal_length": 5.1, "sepal_width": 3.5, "petal_length": 1.4, "petal_width": 0.2, "species": "setosa"},
{"sepal_length": 5.7, "sepal_width": 2.8, "petal_length": 4.1, "petal_width": 1.3, "species": "versicolor"},
{"sepal_length": 6.3, "sepal_width": 2.9, "petal_length": 5.6, "petal_width": 1.8, "species": "virginica"},
{"sepal_length": 6.4, "sepal_width": 3.2, "petal_length": 4.5, "petal_width": 1.5, "species": "versicolor"},
{"sepal_length": 4.7, "sepal_width": 3.2, "petal_length": 1.3, "petal_width": 0.2, "species": "setosa"},
{"sepal_length": 7.0, "sepal_width": 3.2, "petal_length": 4.7, "petal_width": 1.4, "species": "versicolor"},
{"sepal_length": 7.6, "sepal_width": 3.0, "petal_length": 6.6, "petal_width": 2.1, "species": "virginica"},
{"sepal_length": 4.9, "sepal_width": 3.0, "petal_length": 1.4, "petal_width": 0.2, "species": "setosa"}
]""")
# Read JSON data from `FILE`
# type: list[dict]
result = ...