Complete the code to serialize a Python dictionary to a JSON string before storing it in Redis.
import json import redis r = redis.Redis() data = {'name': 'Alice', 'age': 30} r.set('user:1', [1])
We use json.dumps() to convert the Python dictionary into a JSON string before storing it in Redis.
Complete the code to deserialize a JSON string retrieved from Redis back into a Python dictionary.
import json import redis r = redis.Redis() json_data = r.get('user:1') data = [1]
Redis returns bytes, so we decode to a string first, then use json.loads() to convert JSON string to a Python dictionary.
Fix the error in the code that tries to store a Python set in Redis by serializing it.
import json import redis r = redis.Redis() my_set = {1, 2, 3} r.set('myset', [1])
Python sets are not JSON serializable directly. Convert the set to a list first, then serialize.
Fill both blanks to correctly serialize a nested Python object with a datetime before storing it in Redis.
import json import redis from datetime import datetime r = redis.Redis() data = {'event': 'login', 'time': datetime.now()} class DateTimeEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime): return obj.[1]() return super().default(obj) r.set('event', json.dumps(data, cls=[2]))
Use isoformat() to convert datetime to string, and pass the custom encoder class DateTimeEncoder to json.dumps().
Fill all three blanks to deserialize JSON from Redis and convert the datetime string back to a datetime object.
import json import redis from datetime import datetime r = redis.Redis() json_str = r.get('event').decode('utf-8') def datetime_parser(dct): for k, v in dct.items(): if k == '[1]': dct[k] = datetime.[2](v) return dct data = json.loads(json_str, object_hook=[3])
The key holding the datetime string is 'time'. Use datetime.fromisoformat() to convert the string back to datetime. Pass the datetime_parser function as the object_hook to json.loads().