16.3. JSON Load

  • json.load(file) -> object - JSON string to Python object

  • json.loads(str) -> object - JSON string to Python object

  • file extension .json

16.3.1. SetUp

import json

16.3.2. Sequence

DATA = """
["Alice", "Apricot", 30]
"""

result = json.loads(DATA)

print(result)
['Alice', 'Apricot', 30]

16.3.3. Mapping

DATA = """{
    "firstname": "Alice",
    "lastname": "Apricot",
    "age": 30
}"""

result = json.loads(DATA)

print(result)
{'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30}

16.3.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.loads(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.3.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.loads(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.3.6. From 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'}

16.3.7. Assignments

# %% About
# - Name: JSON Load 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. 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ść

# %% Example
# >>> result
# ['Alice', 'Apricot', 30]

# %% Hints
# - `json.loads()`

# %% 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 list, \
'Variable `result` has invalid type, should be list'
>>> assert len(result) > 0, \
'Variable `result` should not be empty'
>>> 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 -v myfile.py`

# %% Imports
import json

# %% Types
result: tuple[str,str,int]

# %% Data
DATA = """
["Alice", "Apricot", 30]
"""

# %% Result
result = ...

# %% About
# - Name: JSON Load 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. 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ść

# %% Example
# >>> result
# {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30}

# %% Hints
# - `json.loads()`

# %% 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 dict, \
'Variable `result` has invalid type, should be dict'
>>> assert len(result) > 0, \
'Variable `result` should not be empty'
>>> assert all(type(row) is str for row in result), \
'Variable `result` should be a dict[str,str|intDATA]'

>>> 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 -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 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. 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ść

# %% Example
# >>> result
# [['firstname', 'lastname', 'age'],
#  ['Alice', 'Apricot', 30],
#  ['Bob', 'Banana', 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 3.9+ required'

>>> 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 list for row in result), \
'Variable `result` should be a list[list]'

>>> from pprint import pprint
>>> pprint(result, width=79, sort_dicts=False)
[['firstname', 'lastname', 'age'],
 ['Alice', 'Apricot', 30],
 ['Bob', 'Banana', 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 -v myfile.py`

# %% Imports
import json

# %% Types
result: list[tuple[str,str,int]]

# %% Data

DATA = """[
    ["firstname", "lastname", "age"],
    ["Alice", "Apricot", 30],
    ["Bob", "Banana", 31],
    ["Carol", "Corn", 32],
    ["Dave", "Durian", 33],
    ["Eve", "Elderberry", 34],
    ["Mallory", "Melon", 15]
]"""


# %% Result
result = ...