0
0
Pythonprogramming~10 mins

Serializing and deserializing JSON in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to convert a Python dictionary to a JSON string.

Python
import json

data = {"name": "Alice", "age": 30}
json_string = json.[1](data)
print(json_string)
Drag options to blanks, or click blank then click option'
Aloads
Bdumps
Cload
Ddump
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'dump' instead of 'dumps' which writes to a file instead of returning a string.
Using 'load' or 'loads' which are for reading JSON, not writing.
2fill in blank
medium

Complete the code to convert a JSON string back to a Python dictionary.

Python
import json

json_string = '{"name": "Bob", "age": 25}'
data = json.[1](json_string)
print(data)
Drag options to blanks, or click blank then click option'
Aload
Bdumps
Cloads
Ddump
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'load' which expects a file object, not a string.
Using 'dump' or 'dumps' which are for writing JSON, not reading.
3fill in blank
hard

Fix the error in the code to correctly write a Python dictionary to a JSON file.

Python
import json

data = {"city": "Paris", "population": 2148327}
with open('data.json', 'w') as file:
    json.[1](data, file)
Drag options to blanks, or click blank then click option'
Adump
Bloads
Cdumps
Dload
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'dumps' which returns a string instead of writing to a file.
Using 'loads' or 'load' which are for reading JSON.
4fill in blank
hard

Fill both blanks to deserialize JSON from a file and print the Python object.

Python
import json

with open('info.json', 'r') as [1]:
    data = json.[2]([1])
print(data)
Drag options to blanks, or click blank then click option'
Afile
Bloads
Cload
Df
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'loads' which expects a string, not a file object.
Using a different variable name inside the block than the one used in 'with open'.
5fill in blank
hard

Fill all three blanks to serialize a Python dictionary with indentation and sort keys.

Python
import json

person = {"name": "Eve", "age": 28, "city": "Berlin"}
json_string = json.[1](person, indent=[2], sort_keys=[3])
print(json_string)
Drag options to blanks, or click blank then click option'
Adump
Bdumps
CTrue
D4
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'dump' which writes to a file instead of returning a string.
Passing indentation as a string instead of a number.
Setting sort_keys to a string instead of a boolean.