有没有库可以为JSON数据生成元组和重构字符串?

2024-06-02 07:57:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我想问一下,是否有一个库可以拆分JSON字符串的“列”和“数据”。你知道吗

目标:

我需要减少在我们开发的遥测系统中传输的数据量。你知道吗

在引擎盖下,字符串化的json数据被交换。如果我能将“列”和“数据”分成不同的部分,我只会交换一次“列”,那么“数据”占用的带宽就会少得多:

orig_data = {"hello": 1, "how_are_you": "good"}
template = "{\"hello\": %d, \"how_are_you\": \"%s\"}"
data = (1, "good")

reconstructed_data = json.loads(template % data) 

template将只交换一次,然后data将更有效地发送。你知道吗

一个更有效的例子是数字输入/输出交换:

orig_data = {"heater_1_started": True, "heater_2_started": False, ..., "heater_76_started": False, "motor_1_running": False, ...}

会变成

data = [0x0345]

那么,有没有库可以获取JSON数据并根据这些信息生成template?你知道吗

编辑

最后,我想要一个自适应协议:

protocol_signature = crc32(template)
if protocol_signature not in synchronized_protocol_signatures: 
    send({'protocol': [protocol_signature, template]})
send([protocol_signature, data])

Tags: 数据字符串jsonfalsehellodatatemplateprotocol
1条回答
网友
1楼 · 发布于 2024-06-02 07:57:52

如果字段总是以相同的顺序发送,则可以使用namedtuple。用您的列名创建一个namedtuple,然后发送数据值并实例化一个namedtuple类的副本。你知道吗

from collections import namedtuple
import json

# Initial column names (send only once)
column_names = ['x', 'y', 'z']

MyData = namedtuple('MyData', column_names)

json_string_from_server = '[True, 1, "good"]'
json_data = json.loads(json_string_from_server)

data = MyData(*json_data)

print data.x, data.y, data.z
# True 1 "good"

至于压缩发送的数据,这取决于您发送的数据类型。如果它主要是任意长度的字符串和整数,那么经过字符串化的json可能已经被尽可能地压缩了。你知道吗

如果主要是要压缩为单个位的开/关布尔标志,则可以使用类似bitarray的库。你知道吗

>>> from bitarray import bitarray
>>> a = bitarray()            # create empty bitarray
>>> a.append(True)
>>> a.extend([False, True, True])
>>> a
bitarray('1011')

相关问题 更多 >