Python
JSON response
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 body
For large bodies, await resp.read() reads bytes; you then decode them into a string with .decode(). Both methods read the body only once.
Exercise 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()).
Show example 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())
Test yourself
-
Complete the json.loads call
import json
text = '{"ad": "Ayşe"}'
data = json.____(text)
Show answer
import json
text = '{"ad": "Ayşe"}'
data = json.loads(text)
-
Which function turns structured data from a string into a dict?
- json.dump
- json.load
- json.dumps
- json.loads
Show answer
json.loads — json.loads(string) turns a string into a dict.
-
Match the structured-data concepts
- await resp.text
- Gives body as string
- json.loads
- Turns string into dict
- import json
- Imports the module
- data['ad']
- Gets value from dict
Next lesson: Summary - HTTP and aiohttp