6.2. JSON String

6.2.1. Mapping

  • json.dumps(DATA: dict) -> str

  • json.loads(DATA: str) -> dict

Serialize mapping to JSON:

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

Deserialize JSON to mapping:

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

6.2.2. List of Mappings

  • json.dumps(data: Sequence[dict]) -> str

  • json.loads(data: str) -> list[dict]

Serialize list of mappings to JSON:

>>> import json
>>>
>>>
>>> DATA = [{'firstname': 'Melissa', 'lastname': 'Lewis'},
...         {'firstname': 'Rick', 'lastname': 'Martinez'},
...         {'firstname': 'Mark', 'lastname': 'Watney'}]
>>>
>>>
>>> result = json.dumps(DATA)
>>>
>>> print(result)  
[{"firstname": "Melissa", "lastname": "Lewis"},
 {"firstname": "Rick", "lastname": "Martinez"},
 {"firstname": "Mark", "lastname": "Watney"}]

Deserialize JSON to list of mappings:

>>> import json
>>>
>>>
>>> DATA = """[
...     {"firstname": "Melissa", "lastname": "Lewis"},
...     {"firstname": "Rick", "lastname": "Martinez"},
...     {"firstname": "Mark", "lastname": "Watney"}]"""
>>>
>>>
>>> result = json.loads(DATA)
>>>
>>> print(result)  
[{'firstname': 'Melissa', 'lastname': 'Lewis'},
 {'firstname': 'Rick', 'lastname': 'Martinez'},
 {'firstname': 'Mark', 'lastname': 'Watney'}]

6.2.3. List of Sequences

  • json.dumps(data: list[Sequence]) -> str

  • json.loads(data: str) -> list[list]

Serialize list of sequences to JSON:

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

Deserialize JSON to list of sequences:

>>> import 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"]]"""
>>>
>>>
>>> result = json.loads(DATA)
>>>
>>> print(result)  
[['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.2.4. Assignments

Code 6.7. Solution
"""
* Assignment: JSON String DumpFlat
* Complexity: easy
* Lines of code: 1 lines
* Time: 2 min

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

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> 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)
    [5.1, 3.5, 1.4, 0.2, "setosa"]
"""

import json


DATA = (5.1, 3.5, 1.4, 0.2, 'setosa')

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

Code 6.8. Solution
"""
* Assignment: JSON String DumpNested
* Complexity: easy
* Lines of code: 1 lines
* Time: 2 min

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

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> 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"]]
"""

import 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')]

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

Code 6.9. Solution
"""
* Assignment: JSON String LoadObject
* Complexity: easy
* Lines of code: 1 lines
* Time: 2 min

English:
    1. Load `DATA` from JSON format
    2. Convert data to `result: dict`
    3. Do not add header as a first line
    4. Run doctests - all must succeed

Polish:
    1. Wczytaj `DATA` z formatu JSON
    2. Przekonwertuj dane do `result: dict`
    3. Nie dodawaj nagłówka jako pierwsza linia
    4. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> 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'

    >>> result  # doctest: +NORMALIZE_WHITESPACE
    {'Sepal length': 5.1,
     'Sepal width': 3.5,
     'Petal length': 1.4,
     'Petal width': 0.2,
     'Species': 'setosa'}
"""

import json


DATA = """
{
    "Sepal length": 5.1,
    "Sepal width": 3.5,
    "Petal length": 1.4,
    "Petal width": 0.2,
    "Species": "setosa"
}
"""


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

Code 6.10. Solution
"""
* Assignment: JSON String LoadList
* Complexity: easy
* Lines of code: 1 lines
* Time: 2 min

English:
    1. Load `DATA` from JSON format
    2. Convert data to `result: list[dict]`
    3. Do not add header as a first line
    4. Run doctests - all must succeed

Polish:
    1. Wczytaj `DATA` z formatu JSON
    2. Przekonwertuj dane do `result: list[dict]`
    3. Nie dodawaj nagłówka jako pierwsza linia
    4. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> 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'}]
"""

import json


DATA = (
    '[{"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 le'
    'ngth":1.4,"Petal width":0.2,"Species":"setosa"},{"Sepal length":5.7,"Sepa'
    'l 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 le'
    'ngth":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"}'
    ']'
)


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