json.loads and dumps
- Python course
- Intermediate
- Lesson 74/116
- 4 min
Learn string JSON with json.loads and dumps.
Working with strings: loads and dumps
Sometimes the data isn't in a file but in a string; for example it arrives from a network request. In that case json.loads(s) turns the string into a Python object; the trailing s stands for string.
In the other direction json.dumps(data) turns a Python object into a string. It doesn't touch files; it works with strings only. dump and load are for files; dumps and loads are for strings.
Practice Convert strings with loads and dumps
Start with import json. Define a string with text = '{"name": "Ayşe", "age": 30}'. Turn the string into a dict with person = json.loads(text). Print the name with print(person["name"]). Then turn the dict back into a string with again = json.dumps(person, ensure_ascii=False) and print it with print(again).
Starter code
import json
# Assign a structured-data string to text
# Convert to a dict with loads, print the name
# Convert back to a string with dumps, printSample solution
import json
# Assign a structured-data string to text
text = '{"name": "Ayşe", "age": 30}'
# Convert to a dict with loads, print the name
person = json.loads(text)
print(person["name"])
# Convert back to a string with dumps, print
again = json.dumps(person, ensure_ascii=False)
print(again)Expected output
Ayşe
{"name": "Ayşe", "age": 30}
load or loads?
Remember the difference easily: load for files, loads for strings. The same rule holds for dump and dumps: write to a file with dump, turn into a string with dumps.
The naming is consistent: the trailing s marks string. So when you see the method name you immediately know whether it uses a file or a string. This reduces confusion and makes code readable.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What type does json.loads accept?
- A number
- A string Correct answer
- A list
- A file object
Explanation: The s in loads stands for string.
2 Complete the json.dumps call
import json
data = {"name": "Ayşe"}
text = json.____(data, ensure_ascii=False)
import json
data = {"name": "Ayşe"}
text = json.dumps(data, ensure_ascii=False)
Explanation: json.dumps turns an object into a string.
3 Match the four methods
| Term | Meaning |
|---|---|
json.load |
Reads from a file |
json.dump |
Writes to a file |
json.loads |
Reads from a string |
json.dumps |
Writes to a string |