Best way to convert json to dict in function python? Need help! or How to properly handle json to dic

22 Replies, 1785 Views

Hey! For json to dict in function python, you could use a decorator to handle errors gracefully.

```python
def handle_json_errors(func):
def wrapper(json_str):
try:
return func(json_str)
except json.JSONDecodeError:
return {"error": "Invalid JSON"}
return wrapper

@handle_json_errors
def json_to_dict(json_str):
return json.loads(json_str)
```

Makes the function cleaner, I think.

Messages In This Thread



Users browsing this thread: 1 Guest(s)