JSON response
- Python course
- Advanced
- Lesson 41/83
- 5 min
Learn JSON responses with await resp.json().
Structured data response
An HTTP response often comes in a structured-data format. You first get the body as a string with await resp.text(), then turn it into a dict with json.loads.
import json
text = await resp.text()
data = json.loads(text)
print(data["ad"])This two-step approach lets you inspect the body and safely parse the structured data. The structured-data module is in the standard library.
await resp.text
await resp.text() returns the response body as a string. This is useful when you want to see the raw body before parsing structured data.
async with session.get(url) as resp:
text = await resp.text()
print(text) # raw bodyFor large bodies, await resp.read() reads bytes; you then decode them into a string with .decode(). Both methods read the body only once.
Practice Read structured data from response
Start with import asyncio, import aiohttp and import json. Inside async def main() open async with aiohttp.ClientSession() as session:. Make a GET request with async with session.get("https://example.com") as resp:. Get the body with text = await resp.text(). Turn it into a dict with data = json.loads(text). Print the name with print(data["ad"]). Add asyncio.run(main()).
Starter code
# load asyncio, aiohttp and the structured-data module
# open a session with async with
# make a get request on the session
# read the body as a string with await
# parse with the loads function and print the name
# run main with asyncio.runSample solution
import asyncio
import aiohttp
import json
class _S:
async def __aenter__(self): return self
async def __aexit__(self, *a): return False
def get(self, url): return self
async def text(self): return '{"ad": "Ayşe"}'
aiohttp.ClientSession = _S
async def main():
async with aiohttp.ClientSession() as session:
async with session.get('https://example.com') as resp:
text = await resp.text()
data = json.loads(text)
print(data['ad'])
asyncio.run(main())Expected output
Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the json.loads call
import json
text = '{"ad": "Ayşe"}'
data = json.____(text)
import json
text = '{"ad": "Ayşe"}'
data = json.loads(text)
Explanation: json.loads(string) turns a string into a dict.
2 Which function turns structured data from a string into a dict?
- json.dump
- json.load
- json.dumps
- json.loads Correct answer
Explanation: json.loads(string) turns a string into a dict.
3 Match the structured-data concepts
| Term | Meaning |
|---|---|
await resp.text |
Gives body as string |
json.loads |
Turns string into dict |
import json |
Imports the module |
data['ad'] |
Gets value from dict |