16.2. JSON Dump
json.dumps(object) -> str
- Python object to JSON stringjson.dump(object) -> file
- Python object to JSON filefile extension
.json
16.2.1. SetUp
import json
16.2.2. Sequence
DATA = ('Alice', 'Apricot', 30)
result = json.dumps(DATA)
print(result)
["Alice", "Apricot", 30]
16.2.3. Mapping
DATA = {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30}
result = json.dumps(DATA)
print(result)
{"firstname": "Alice", "lastname": "Apricot", "age": 30}
16.2.4. List of Sequence
DATA = [
('firstname', 'lastname', 'age'),
('Alice', 'Apricot', 30),
('Bob', 'Banana', 31),
('Carol', 'Corn', 32),
('Dave', 'Durian', 33),
('Eve', 'Elderberry', 34),
('Mallory', 'Melon', 15),
]
result = json.dumps(DATA)
print(result)
[["firstname", "lastname", "age"],
["Alice", "Apricot", 30],
["Bob", "Banana", 31],
["Carol", "Corn", 32],
["Dave", "Durian", 33],
["Eve", "Elderberry", 34],
["Mallory", "Melon", 15]]
16.2.5. List of Mappings
DATA = [
{'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30},
{'firstname': 'Bob', 'lastname': 'Banana', 'age': 31},
{'firstname': 'Carol', 'lastname': 'Corn', 'age': 32},
{'firstname': 'Dave', 'lastname': 'Durian', 'age': 33},
{'firstname': 'Eve', 'lastname': 'Elderberry', 'age': 34},
{'firstname': 'Mallory', 'lastname': 'Melon', 'age': 15},
]
result = json.dumps(DATA)
print(result)
[{"firstname": "Alice", "lastname": "Apricot", "age": 30},
{"firstname": "Bob", "lastname": "Banana", "age": 31},
{"firstname": "Carol", "lastname": "Corn", "age": 32},
{"firstname": "Dave", "lastname": "Durian", "age": 33},
{"firstname": "Eve", "lastname": "Elderberry", "age": 34},
{"firstname": "Mallory", "lastname": "Melon", "age": 15}]
16.2.6. To 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': 'Alice', 'lastname': 'Apricot', 'age': 30}
Usage:
with open('/tmp/myfile.json', mode='wt') as file:
json.dump(DATA, file)
Result:
result = open('/tmp/myfile.json').read()
print(result)
{"firstname": "Alice", "lastname": "Apricot", "age": 30}
16.2.7. Assignments
# %% About
# - Name: JSON Dump Sequence
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2
# %% 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
# %% English
# 1. Serialize data from variable `DATA`
# 2. Use `json` module
# 3. Result write to variable `result`
# 4. Run doctests - all must succeed
# %% Polish
# 1. Zserializuj dane ze zmiennej `DATA`
# 2. Użyj modułu `json`
# 3. Wynik zapisz do zmiennej `result`
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# >>> result
# ["Alice", "Apricot", 30]
# %% Hints
# - `json.dumps()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> 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)
["Alice", "Apricot", 30]
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
import json
# %% Types
result: str
# %% Data
DATA = ('Alice', 'Apricot', 30)
# %% Result
result = ...
# %% About
# - Name: JSON Dump Mapping
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2
# %% 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
# %% English
# 1. Serialize data from variable `DATA`
# 2. Use `json` module
# 3. Result write to variable `result`
# 4. Run doctests - all must succeed
# %% Polish
# 1. Zserializuj dane ze zmiennej `DATA`
# 2. Użyj modułu `json`
# 3. Wynik zapisz do zmiennej `result`
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Hints
# - `json.dumps()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> 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)
{"firstname": "Mark", "lastname": "Watney", "age": 41}
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
import json
# %% Types
result: str
# %% Data
DATA = {'firstname': 'Mark', 'lastname': 'Watney', 'age': 41}
# %% Result
result = ...
# %% About
# - Name: JSON Dump ListSequence
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2
# %% 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
# %% English
# 1. Serialize data from variable `DATA`
# 2. Use `json` module
# 3. Result write to variable `result`
# 4. Run doctests - all must succeed
# %% Polish
# 1. Zserializuj dane ze zmiennej `DATA`
# 2. Użyj modułu `json`
# 3. Wynik zapisz do zmiennej `result`
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Hints
# - `json.dumps()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> 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
[["firstname", "lastname", "age"],
["Mark", "Watney", 41],
["Melissa", "Lewis", 40],
["Rick", "Martinez", 39],
["Alex", "Vogel", 40],
["Chris", "Beck", 36],
["Beth", "Johanssen", 29]]
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
import json
# %% Types
result: str
# %% Data
DATA = [
('firstname', 'lastname', 'age'),
('Mark', 'Watney', 41),
('Melissa', 'Lewis', 40),
('Rick', 'Martinez', 39),
('Alex', 'Vogel', 40),
('Chris', 'Beck', 36),
('Beth', 'Johanssen', 29),
]
# %% Result
result = ...
# %% About
# - Name: JSON Dump ListMapping
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2
# %% 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
# %% English
# 1. Serialize data from variable `DATA`
# 2. Use `json` module
# 3. Result write to variable `result`
# 4. Run doctests - all must succeed
# %% Polish
# 1. Zserializuj dane ze zmiennej `DATA`
# 2. Użyj modułu `json`
# 3. Wynik zapisz do zmiennej `result`
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Hints
# - `json.dumps()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> 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
[{"firstname": "Mark", "lastname": "Watney", "age": 41},
{"firstname": "Melissa", "lastname": "Lewis", "age": 40},
{"firstname": "Rick", "lastname": "Martinez", "age": 39},
{"firstname": "Alex", "lastname": "Vogel", "age": 40},
{"firstname": "Chris", "lastname": "Beck", "age": 36},
{"firstname": "Beth", "lastname": "Johanssen", "age": 29}]
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
import json
# %% Types
result: str
# %% Data
DATA = [
{'firstname': 'Mark', 'lastname': 'Watney', 'age': 41},
{'firstname': 'Melissa', 'lastname': 'Lewis', 'age': 40},
{'firstname': 'Rick', 'lastname': 'Martinez', 'age': 39},
{'firstname': 'Alex', 'lastname': 'Vogel', 'age': 40},
{'firstname': 'Chris', 'lastname': 'Beck', 'age': 36},
{'firstname': 'Beth', 'lastname': 'Johanssen', 'age': 29},
]
# %% Result
result = ...
# %% About
# - Name: JSON Dump ToFile
# - Difficulty: easy
# - Lines: 2
# - Minutes: 3
# %% 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
# %% English
# 1. Serialize data from variable `DATA`
# 2. Use `json` module
# 3. Result write to file `FILE`
# 4. Run doctests - all must succeed
# %% Polish
# 1. Zserializuj dane ze zmiennej `DATA`
# 2. Użyj modułu `json`
# 3. Wynik zapisz do pliku `FILE`
# 4. Uruchom doctesty - wszystkie muszą się powieść
# %% Hints
# - `with open(mode='wt') as file:`
# - `json.dump()`
# %% Doctests
"""
>>> 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"]]
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
import json
# %% Types
# %% Data
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'),
]
# %% Result