【问题标题】:Issue serializing JSON data序列化 JSON 数据的问题
【发布时间】: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


【解决方案1】:

这个问题终于解决了!

这是因为在我的类定义中,我不小心在属性定义之后留下了尾随逗号,导致它们被视为Tuples 而不是单数项。

该类应如下所示:

class Alert(object):
    def __init__(self, alerttype, timestamp, reading, message):
        self.alerttype = alerttype  # <- Trailing commas removed
        self.timestamp = timestamp
        self.reading = reading
        self.message = message

在这些线程的帮助下解决了:

Python explicitly define object attribute type

member variable string gets treated as Tuple in Python

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 2021-05-28
    • 1970-01-01
    相关资源
    最近更新 更多