brendan-w / python-OBD

OBD-II serial module for reading engine data
GNU General Public License v2.0
1.06k stars 369 forks source link

Serialize OBDResponse to JSON #216

Open NaturesProphet opened 3 years ago

NaturesProphet commented 3 years ago

Hello folks.

Please, i need some help to serialize OBDResponse objects to JSON, any idea about how can i do it? i'm new to python.

ConnorNovak commented 3 years ago

Being more specific with your request will help you get help:

NaturesProphet commented 3 years ago

Hello Connor, thanks for reading this.

I want to serialize the entire and arbitrary OBDResponse object to json and use this json as a response on an flask rest endpoint that i am integrating with the obd. my objective is to serve a http rest api that will respond with OBDResponse as a json, and i want all the nested documents inside that object.

well, as i said, i'm new to python, my home language is javascript and it would be really easy to do such task on that language without write a logic for each field. i want something in javascript way if possible.

ConnorNovak commented 3 years ago

My personal opinion: Your best bet would be creating a function that serializes a given OBDResponse object. Looking at the documentation for the object, it appears to have four salient attributes (you should probably include the units property as well, so make it 5): command, messages, value, time, and units. It looks, at first glance, like each of these can be cast to a base type. A single function should then suffice for any OBDResponse.

If you wanted to contribute to the library, you could make an as_json() method for OBDResponse, or something similar. You could also drop your function in utils.py. I'm not associated with this repository in any way, so I can't say what reception if would have.

Salient code points: https://github.com/brendan-w/python-OBD/blob/master/obd/obd.py line 298: Creation of OBDResponse object https://github.com/brendan-w/python-OBD/blob/master/obd/OBDCommand.py line 85: unpacking of response data into OBDResponse object

bgunson commented 2 years ago

Hi, I wrote a JSON encoder which works for most of the python-OBD types.

Check it out at https://github.com/bgunson/obd-socketio

To use it pip install obd-socketio

import obdio

obdio.dumps(...)
obdio.dump(...)  

Contribution is also welcome becuase its not fully implemented but does the job.

NaturesProphet commented 2 years ago

awesome dude