是否有任何库可以为 JSON 数据生成元组和重建字符串



我想问一下是否有一个库可以拆分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])

如果字段始终以相同的顺序发送,则可以使用 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 可能已经尽可能压缩了。

如果主要是要压缩为单个位的开/关布尔标志,则可以使用像位数组这样的库。

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

最新更新