5
company = self.env['res.company'].search([('id', '=', 1)])
print company.name # prints 'my company' which is correct
print json.dumps(company) # error TypeError: res.company(1,) is not JSON serializable

Question is how do simply export company object in json?

I am looking for a generic way which would work for any model.

user1
  • 4,031
  • 8
  • 37
  • 66
  • 1
    I am looking for this too. It's kind of insane that this is such a hassle. Coming from a JS background this is quite frustrating that you can't get a read on the objects that you're processing during development. Is there a fix at all?!! – Ragav Y Jan 06 '20 at 07:13

4 Answers4

3

Use Model.read(). You can also specify the fields to be read in the read method (see doc). Also, datetime objects are not json serializable. Fortunately, Odoo already provides a utility method.

import json
from odoo.tools import date_utils

raw_data = company.read()
json_data = json.dumps(raw_data, default=date_utils.json_default)
print(json_data)
Jerther
  • 5,558
  • 8
  • 40
  • 59
1

Please try this code:

company = self.env['res.company'].search([('id', '=', 1)])
print company.name
print json.dumps(company.name)
Bhoomi Vaishnani
  • 718
  • 4
  • 19
0

Search will return object, so we have to manually add fields to dictionary to build the json. I have added few fields, you can add more fields.

company = self.env['res.company'].search([('id', '=', 1)])
params = {}
data = dict()
data['partner_id'] = company.partner_id
data['name'] = company.name
data['email'] = company.email
data['phone'] = company.phone
data['company_registry'] = company.company_registry
params['params'] = data
print json.dumps(params)
Kiran
  • 1,481
  • 6
  • 36
  • 66
  • This is very crude. The solution I am looking for should automatically read all field names and put them as keys, read values of these fields and assign them to respective keys and prepare json. Kind of generic function. – user1 Jul 04 '18 at 03:08
0

The last answer (Jerther) is the right answer.

You can also use in odoo 16

from odoo.tools import json_default

instead of

from odoo.tools import date_utils
Tyler2P
  • 2,324
  • 26
  • 22
  • 31