15.3. JSON Load — Python
json.load(file) -> object- JSON string to Python objectjson.loads(str) -> object- JSON string to Python objectfile extension
.json
15.3.1. SetUp
15.3.2. Sequence
>>> DATA = """ ... ["Alice", "Apricot", 30] ... """ >>> >>> result = json.loads(DATA) >>> >>> print(result) ['Alice', 'Apricot', 30]
15.3.3. List of Sequences
>>> DATA = """[ ... ["firstname", "lastname", "age"], ... ["Alice", "Apricot", 30], ... ["Bob", "Blackthorn", 31], ... ["Carol", "Corn", 32], ... ["Dave", "Durian", 33], ... ["Eve", "Elderberry", 34], ... ["Mallory", "Melon", 15] ... ]""" >>> >>> result = json.loads(DATA) >>> >>> print(result) [['firstname', 'lastname', 'age'], ['Alice', 'Apricot', 30], ['Bob', 'Blackthorn', 31], ['Carol', 'Corn', 32], ['Dave', 'Durian', 33], ['Eve', 'Elderberry', 34], ['Mallory', 'Melon', 15]]
15.3.4. Mapping
>>> DATA = """{ ... "firstname": "Alice", ... "lastname": "Apricot", ... "age": 30 ... }""" >>> >>> result = json.loads(DATA) >>> >>> print(result) {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30}
15.3.5. List of Mappings
>>> DATA = """[ ... {"firstname": "Alice", "lastname": "Apricot", "age": 30}, ... {"firstname": "Bob", "lastname": "Blackthorn", "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.loads(DATA) >>> >>> print(result) [{'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30}, {'firstname': 'Bob', 'lastname': 'Blackthorn', '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}]
15.3.6. From File
json.load(file) -> dictfile 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": "Alice", ... "lastname": "Apricot" ... }""" >>> >>> _ = open('/tmp/myfile.json', mode='w').write(DATA)
Usage:
>>> with open('/tmp/myfile.json') as file: ... result = json.load(file) >>> >>> print(result) {'firstname': 'Alice', 'lastname': 'Apricot'}
15.3.7. Assignments
# %% About # - Name: JSON Load Sequence # - Difficulty: easy # - Lines: 1 # - Minutes: 1 # %% 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. Deserialize data from variable `DATA` # 2. Use `json` module # 3. Result write to variable `result` # 4. Run doctests - all must succeed # %% Polish # 1. Zdeserializuj dane ze zmiennej `DATA` # 2. Użyj modułu `json` # 3. Wynik zapisz do zmiennej `result` # 4. Uruchom doctesty - wszystkie muszą się powieść # %% Expected # >>> result # ['Alice', 'Apricot', 30] # %% Hints # - `json.loads()` # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> assert 'result' in globals(), \ 'Variable `result` is not defined; assign result of your program to it.' >>> assert result is not Ellipsis, \ 'Variable `result` has an invalid value; assign result of your program to it.' >>> assert type(result) is list, \ 'Variable `result` has an invalid type; expected: `list`.' >>> assert len(result) > 0, \ 'Variable `result` has an invalid length; expected more than zero elements.' >>> assert all(type(row) in (str,int) for row in result), \ 'Variable `result` should be a list[str|int]' >>> from pprint import pprint >>> pprint(result, width=79, sort_dicts=False) ['Alice', 'Apricot', 30] """ # %% Run # - PyCharm: right-click in the editor and `Run Doctest in ...` # - PyCharm: keyboard shortcut `Control + Shift + F10` # - Terminal: `python -m doctest -f -v myfile.py` # %% Imports import json # %% Types result: tuple[str,str,int] # %% Data DATA = """ ["Alice", "Apricot", 30] """ # %% Result result = ...
# %% About # - Name: JSON Load ListSequence # - Difficulty: easy # - Lines: 1 # - Minutes: 1 # %% 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. Deserialize data from variable `DATA` # 2. Use `json` module # 3. Result write to variable `result` # 4. Run doctests - all must succeed # %% Polish # 1. Zdeserializuj dane ze zmiennej `DATA` # 2. Użyj modułu `json` # 3. Wynik zapisz do zmiennej `result` # 4. Uruchom doctesty - wszystkie muszą się powieść # %% Expected # >>> result # [['firstname', 'lastname', 'age'], # ['Alice', 'Apricot', 30], # ['Bob', 'Blackthorn', 31], # ['Carol', 'Corn', 32], # ['Dave', 'Durian', 33], # ['Eve', 'Elderberry', 34], # ['Mallory', 'Melon', 15]] # %% Hints # - `json.loads()` # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> assert 'result' in globals(), \ 'Variable `result` is not defined; assign result of your program to it.' >>> assert result is not Ellipsis, \ 'Variable `result` has an invalid value; assign result of your program to it.' >>> assert type(result) is list, \ 'Variable `result` has an invalid type; expected: `list`.' >>> assert len(result) > 0, \ 'Variable `result` has an invalid length; expected more than zero elements.' >>> assert all(type(x) is list for x in result), \ 'Variable `result` has elements of an invalid type; all items should be: `list`.' >>> from pprint import pprint >>> pprint(result, width=79, sort_dicts=False) [['firstname', 'lastname', 'age'], ['Alice', 'Apricot', 30], ['Bob', 'Blackthorn', 31], ['Carol', 'Corn', 32], ['Dave', 'Durian', 33], ['Eve', 'Elderberry', 34], ['Mallory', 'Melon', 15]] """ # %% Run # - PyCharm: right-click in the editor and `Run Doctest in ...` # - PyCharm: keyboard shortcut `Control + Shift + F10` # - Terminal: `python -m doctest -f -v myfile.py` # %% Imports import json # %% Types result: list[tuple[str,str,int]] # %% Data DATA = """[ ["firstname", "lastname", "age"], ["Alice", "Apricot", 30], ["Bob", "Blackthorn", 31], ["Carol", "Corn", 32], ["Dave", "Durian", 33], ["Eve", "Elderberry", 34], ["Mallory", "Melon", 15] ]""" # %% Result result = ...
# %% About # - Name: JSON Load Mapping # - Difficulty: easy # - Lines: 1 # - Minutes: 1 # %% 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. Deserialize data from variable `DATA` # 2. Use `json` module # 3. Result write to variable `result` # 4. Run doctests - all must succeed # %% Polish # 1. Zdeserializuj dane ze zmiennej `DATA` # 2. Użyj modułu `json` # 3. Wynik zapisz do zmiennej `result` # 4. Uruchom doctesty - wszystkie muszą się powieść # %% Expected # >>> result # {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30} # %% Hints # - `json.loads()` # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> assert 'result' in globals(), \ 'Variable `result` is not defined; assign result of your program to it.' >>> assert result is not Ellipsis, \ 'Variable `result` has an invalid value; assign result of your program to it.' >>> assert type(result) is dict, \ 'Variable `result` has an invalid type; expected: `dict`.' >>> assert len(result) > 0, \ 'Variable `result` has an invalid length; expected more than zero elements.' >>> assert all(type(x) is str for x in result), \ 'Variable `result` has elements of an invalid type; all items should be: `str`.' >>> from pprint import pprint >>> pprint(result, width=80, sort_dicts=False) {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30} """ # %% Run # - PyCharm: right-click in the editor and `Run Doctest in ...` # - PyCharm: keyboard shortcut `Control + Shift + F10` # - Terminal: `python -m doctest -f -v myfile.py` # %% Imports import json # %% Types result: dict[str,str|int] # %% Data DATA = """ {"firstname": "Alice", "lastname": "Apricot", "age": 30} """ # %% Result result = ...
# %% About # - Name: JSON Load ListMapping # - Difficulty: easy # - Lines: 1 # - Minutes: 1 # %% 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. Deserialize data from variable `DATA` # 2. Use `json` module # 3. Result write to variable `result` # 4. Run doctests - all must succeed # %% Polish # 1. Zdeserializuj dane ze zmiennej `DATA` # 2. Użyj modułu `json` # 3. Wynik zapisz do zmiennej `result` # 4. Uruchom doctesty - wszystkie muszą się powieść # %% Expected # >>> result # [{'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30}, # {'firstname': 'Bob', 'lastname': 'Blackthorn', '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}] # %% Hints # - `json.loads()` # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> assert 'result' in globals(), \ 'Variable `result` is not defined; assign result of your program to it.' >>> assert result is not Ellipsis, \ 'Variable `result` has an invalid value; assign result of your program to it.' >>> assert type(result) is list, \ 'Variable `result` has an invalid type; expected: `list`.' >>> assert len(result) > 0, \ 'Variable `result` has an invalid length; expected more than zero elements.' >>> assert all(type(x) is dict for x in result), \ 'Variable `result` has elements of an invalid type; all items should be: `dict`.' >>> from pprint import pprint >>> pprint(result, width=79, sort_dicts=False) [{'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30}, {'firstname': 'Bob', 'lastname': 'Blackthorn', '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}] """ # %% Run # - PyCharm: right-click in the editor and `Run Doctest in ...` # - PyCharm: keyboard shortcut `Control + Shift + F10` # - Terminal: `python -m doctest -f -v myfile.py` # %% Imports import json # %% Types result: list[dict[str, str|int]] # %% Data DATA = """[ {"firstname": "Alice", "lastname": "Apricot", "age": 30}, {"firstname": "Bob", "lastname": "Blackthorn", "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 result = ...
# %% About # - Name: JSON Load FromFile # - Difficulty: easy # - Lines: 2 # - 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. Deserialize data from file `FILE` # 2. Use `json` module # 3. Result write to variable `result` # 4. Run doctests - all must succeed # %% Polish # 1. Zdeserializuj dane z pliku `FILE` # 2. Użyj modułu `json` # 3. Wynik zapisz do zmiennej `result` # 4. Uruchom doctesty - wszystkie muszą się powieść # %% Expected # >>> result # [{'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30}, # {'firstname': 'Bob', 'lastname': 'Blackthorn', '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}] # %% Hints # - `json.load()` # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> assert 'result' in globals(), \ 'Variable `result` is not defined; assign result of your program to it.' >>> assert result is not Ellipsis, \ 'Variable `result` has an invalid value; assign result of your program to it.' >>> assert type(result) is list, \ 'Variable `result` has an invalid type; expected: `list`.' >>> assert len(result) > 0, \ 'Variable `result` has an invalid length; expected more than zero elements.' >>> assert all(type(x) is dict for x in result), \ 'Variable `result` has elements of an invalid type; all items should be: `dict`.' >>> from os import remove >>> remove(FILE) >>> from pprint import pprint >>> pprint(result, width=79, sort_dicts=False) [{'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30}, {'firstname': 'Bob', 'lastname': 'Blackthorn', '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}] """ # %% Run # - PyCharm: right-click in the editor and `Run Doctest in ...` # - PyCharm: keyboard shortcut `Control + Shift + F10` # - Terminal: `python -m doctest -f -v myfile.py` # %% Imports import json # %% Types result: list[dict[str, str|int]] # %% Data FILE = r'_temporary.json' with open(FILE, mode='wt') as file: file.write(""" [ {"firstname": "Alice", "lastname": "Apricot", "age": 30}, {"firstname": "Bob", "lastname": "Blackthorn", "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 result = ...