Skip to content

Commit 19b99d1

Browse files
authored
Update iot_ext_item_data_builder.py for Decimal serialization in JSON (#33)
* Update iot_ext_item_data_builder.py for Decimal serialization in JSON * Update iot_ext_item_data_builder.py * Update iot_ext_item_data_builder.py
1 parent 1ef8dd2 commit 19b99d1

1 file changed

Lines changed: 17 additions & 1 deletion

File tree

src/builders/iot_ext_item_data_builder.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import json
2+
import decimal
23
from decimal import Decimal
34
from typing import List, Optional
45

@@ -12,6 +13,21 @@
1213
from src.types.metric_data_item import MetricValueType, MetricDataItem
1314

1415

16+
class fakefloat(float):
17+
def __init__(self, value):
18+
self._value = value
19+
20+
def __repr__(self):
21+
return str(self._value)
22+
23+
24+
def defaultencode(o):
25+
if isinstance(o, Decimal):
26+
# Subclass float with custom repr?
27+
return fakefloat(o)
28+
raise TypeError(repr(o) + " is not JSON serializable")
29+
30+
1531
class IoTextItemDataBuilder:
1632
def __init__(
1733
self, timestamp: int, device_name: str, add_crc16: bool = False
@@ -80,7 +96,7 @@ def iotext_to_json_one_object(iotext_msg) -> str:
8096
else:
8197
data_row[item.kind] = item.name
8298
data_row.update(data_row)
83-
return json.dumps(data_row)
99+
return json.dumps(data_row, default=defaultencode)
84100

85101
@staticmethod
86102
def to_json_from_iotext_struct(

0 commit comments

Comments
 (0)