How to Implement json.loads() in Odoo?
What is json.loads()?
- json.loads() is a Python function from the json module that converts a JSON-formatted string into a Python dictionary or list.
- “loads” stands for load string.
✅ Syntax
import json
python_obj = json.loads(json_string)
- json_string: A string in JSON format (e.g., from a web request or field).
- python_obj: Resulting Python dictionary or list.
📌 Realistic Use Cases in Odoo
1. Handling JSON Data from a Web Controller
In Odoo, JSON data is commonly sent from a website or JavaScript call to a controller:
@http.route('/custom/api/submit', type='json', auth='user')
def submit_data(self, **kwargs):
data = json.loads(kwargs.get('payload'))
name = data.get('name')
email = data.get('email')
# Process data
return {'status': 'success'}
Here, json.loads() converts the incoming JSON string to a Python dict for use in server-side logic.
2. Reading JSON Stored in Char/Text Fields
Odoo may store serialized JSON in a Text field (e.g., product specs or settings):
specs = json.loads(record.spec_json)
if specs.get('warranty') == 'yes':
record.message_post(body="Product has warranty.")
3. Parsing External API Response (in Custom Integrations)
When working with external APIs in Odoo:
response = requests.get('https://api.example.com/data')
data = json.loads(response.text)
for item in data.get('items', []):
self.env['external.record'].create({
'name': item['title'],
'code': item['id'],
})
✅ Summary Table
Function | Purpose | Odoo Use Case |
json.loads() | Convert JSON string → Python object | Controller data, custom field, external API |