【发布时间】:2021-02-05 09:23:17
【问题描述】:
我正在尝试将我的 Python 对象序列化为 JSON。我已经设法让它成功地正确序列化,但是它似乎正在将所有内容(包括单个值)序列化为数组。我希望输出尽可能精简,将单个值与它们的键值一起打印在同一行。我似乎在用这样保存的值解析保存的 JSON 时遇到问题。
这是我得到的输出的 sn-p:
{
"sensorid": [
"b8:27:eb:f3:b0:e0"
],
"temperature": [
17
],
...
然而,理想情况下,我希望这个 sn-p 看起来像:
{
"sensorid": "b8:27:eb:f3:b0:e0",
"temperature": 17,
...
这是我用来生成它的代码:
class Alert(object):
def __init__(self, alerttype, timestamp, reading, message):
self.alerttype = alerttype,
self.timestamp = timestamp,
self.reading = reading,
self.message = message
class Packet(object):
def __init__(self, sensorid, temperature, humidity, fan_on, fan_speed, vent_open, alerts: List[Alert]):
self.sensorid = sensorid,
self.temperature = temperature,
self.humidity = humidity,
self.fan_on = fan_on,
self.fan_speed = fan_speed,
self.vent_open = vent_open,
self.alerts = alerts
testA = Alert(0, int(math.floor(time.time())), "", "DHTLIB_ERROR_CHECKSUM")
testB = Alert(1, int(math.floor(time.time())), "", "DHTLIB_ERROR_CHECKSUM")
testC = Alert(2, int(math.floor(time.time())), "", "DHTLIB_ERROR_CHECKSUM")
testP = Packet("b8:27:eb:f3:b0:e0", int(17), int(23), "True", 100, True, [])
testP.alerts.append(testA)
testP.alerts.append(testB)
testP.alerts.append(testC)
jsonStr = json.dumps(testP.__dict__, default=lambda x: x.__dict__, indent=4)
print(jsonStr)
我错过了什么导致它以这种方式输出吗?
我会很感激任何人的想法,TIA。
【问题讨论】:
-
我会说通过
testP.__dict__不是最好的解决方案。编写serialize方法会不会更好,它会按预期返回所有内容?但可能等待更多意见:) -
@DawidGacek 我确实考虑过,虽然我希望可能有一个更整洁的库函数方法
标签: python json serialization format