18.2. JSON String

  • json.dumps(DATA: object) -> str - object to string (JSON)

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

18.2.1. SetUp

>>> import json

18.2.2. Sequence

Serialize:

>>> DATA = ('Mark', 'Watney', 41)
>>>
>>> result = json.dumps(DATA)
>>> print(result)
["Mark", "Watney", 41]

Deserialize:

>>> DATA = """
... ["Mark", "Watney", 41]
... """
>>>
>>> result = json.loads(DATA)
>>> print(result)
['Mark', 'Watney', 41]

18.2.3. Mapping

Serialize:

>>> DATA = {
...     'firstname': 'Mark',
...     'lastname': 'Watney',
...     'age': 41,
... }
>>>
>>> result = json.dumps(DATA)
>>> print(result)
{"firstname": "Mark", "lastname": "Watney", "age": 41}

Deserialize:

>>> DATA = """{
...     "firstname": "Mark",
...     "lastname": "Watney",
...     "age": 41
... }"""
>>>
>>> result = json.loads(DATA)
>>> print(result)
{'firstname': 'Mark', 'lastname': 'Watney', 'age': 41}

18.2.4. List of Sequence

Serialize:

>>> DATA = [
...     ('firstname', 'lastname', 'age'),
...     ('Mark', 'Watney', 41),
...     ('Melissa', 'Lewis', 40),
...     ('Rick', 'Martinez', 39),
...     ('Alex', 'Vogel', 40),
...     ('Chris', 'Beck', 36),
...     ('Beth', 'Johanssen', 29),
... ]
>>>
>>> result = json.dumps(DATA)
>>> print(result)  
[["firstname", "lastname", "age"],
 ["Mark", "Watney", 41],
 ["Melissa", "Lewis", 40],
 ["Rick", "Martinez", 39],
 ["Alex", "Vogel", 40],
 ["Chris", "Beck", 36],
 ["Beth", "Johanssen", 29]]

Deserialize:

>>> DATA = """[
...     ["firstname", "lastname", "age"],
...     ["Mark", "Watney", 41],
...     ["Melissa", "Lewis", 40],
...     ["Rick", "Martinez", 39],
...     ["Alex", "Vogel", 40],
...     ["Chris", "Beck", 36],
...     ["Beth", "Johanssen", 29]
... ]"""
>>>
>>> result = json.loads(DATA)
>>> print(result)  
[['firstname', 'lastname', 'age'],
 ['Mark', 'Watney', 41],
 ['Melissa', 'Lewis', 40],
 ['Rick', 'Martinez', 39],
 ['Alex', 'Vogel', 40],
 ['Chris', 'Beck', 36],
 ['Beth', 'Johanssen', 29]]

18.2.5. List of Mappings

Serialize:

>>> 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 = json.dumps(DATA)
>>> print(result)  
[{"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}]

Deserialize:

>>> 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 = json.loads(DATA)
>>> print(result)  
[{'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}]

18.2.6. 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 String DumpFlat
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Dump `DATA` to JSON format
# 2. Run doctests - all must succeed

# %% Polish
# 1. Zrzuć `DATA` do formatu JSON
# 2. Uruchom doctesty - wszystkie muszą się powieść

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

# %% Tests
"""
>>> 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)
["Mark", "Watney", 41]
"""

import json


DATA = ('Mark', 'Watney', 41)

# dump DATA to JSON format
# type: str
result = ...


# %% 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 String DumpFlat
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Dump `DATA` to JSON format
# 2. Run doctests - all must succeed

# %% Polish
# 1. Zrzuć `DATA` do formatu JSON
# 2. Uruchom doctesty - wszystkie muszą się powieść

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

# %% Tests
"""
>>> 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}
"""

import json


DATA = {'firstname': 'Mark', 'lastname': 'Watney', 'age': 41}

# dump DATA to JSON format
# type: str
result = ...


# %% 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 String DumpNested
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Dump `DATA` to JSON format
# 2. Run doctests - all must succeed

# %% Polish
# 1. Zrzuć `DATA` do formatu JSON
# 2. Uruchom doctesty - wszystkie muszą się powieść

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

# %% Tests
"""
>>> 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]]
"""

import json


DATA = [
    ('firstname', 'lastname', 'age'),
    ('Mark', 'Watney', 41),
    ('Melissa', 'Lewis', 40),
    ('Rick', 'Martinez', 39),
    ('Alex', 'Vogel', 40),
    ('Chris', 'Beck', 36),
    ('Beth', 'Johanssen', 29),
]

# dump DATA to JSON format
# type: str
result = ...


# %% 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 String DumpNested
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Dump `DATA` to JSON format
# 2. Run doctests - all must succeed

# %% Polish
# 1. Zrzuć `DATA` do formatu JSON
# 2. Uruchom doctesty - wszystkie muszą się powieść

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

# %% Tests
"""
>>> 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}]
"""

import json


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},
]

# Dump DATA to JSON format
# type: str
result = ...


# %% 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 String LoadObject
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Load `DATA` from JSON format
# 2. Convert data to `result: list[dict]`
# 3. Run doctests - all must succeed

# %% Polish
# 1. Wczytaj `DATA` z formatu JSON
# 2. Przekonwertuj dane do `result: list[dict]`
# 3. Uruchom doctesty - wszystkie muszą się powieść

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

# %% Tests
"""
>>> 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'

>>> from pprint import pprint
>>> pprint(result, width=80, sort_dicts=False)
[{'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}]
"""

import json


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}
]
"""


# Load `DATA` from JSON format
# Convert data to `result: list[dict]`
# type: list[dict]
result = ...


# %% 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 String LoadList
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Load `DATA` from JSON format
# 2. Convert data to `result: list[dict]`
# 3. Run doctests - all must succeed

# %% Polish
# 1. Wczytaj `DATA` z formatu JSON
# 2. Przekonwertuj dane do `result: list[dict]`
# 3. Uruchom doctesty - wszystkie muszą się powieść

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

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

>>> result[0]  # doctest: +NORMALIZE_WHITESPACE
{'sepal_length': 5.8,
 'sepal_width': 2.7,
 'petal_length': 5.1,
 'petal_width': 1.9,
 'species': 'virginica'}

>>> 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


DATA = (
    '[{"sepal_length":5.8,"sepal_width":2.7,"petal_length":5.1,"petal_widt'
    'h":1.9,"species":"virginica"},{"sepal_length":5.1,"sepal_width":3.5,"'
    'petal_length":1.4,"petal_width":0.2,"species":"setosa"},{"sepal_lengt'
    'h":5.7,"sepal_width":2.8,"petal_length":4.1,"petal_width":1.3,"specie'
    's":"versicolor"},{"sepal_length":6.3,"sepal_width":2.9,"petal_length"'
    ':5.6,"petal_width":1.8,"species":"virginica"},{"sepal_length":6.4,"se'
    'pal_width":3.2,"petal_length":4.5,"petal_width":1.5,"species":"versic'
    'olor"},{"sepal_length":4.7,"sepal_width":3.2,"petal_length":1.3,"peta'
    'l_width":0.2,"species":"setosa"},{"sepal_length":7.0,"sepal_width":3.'
    '2,"petal_length":4.7,"petal_width":1.4,"species":"versicolor"},{"sepa'
    'l_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_l'
    'ength":1.4,"petal_width":0.2,"species":"setosa"}]'
)


# Load `DATA` from JSON format
# type: list[dict]
result = ...