【发布时间】:2021-08-03 19:30:09
【问题描述】:
我正在使用最新版本的 micropython。我还使用了 DS18b20 温度传感器。这些传感器的地址,例如是“b'(b\xe5V\xb5\x01<: json>
- 如果我在读取 json 文件后直接存储 "b'(b\xe5V\xb5\x01<: python b>
- 如果我转义像 "b'(b\xe5V\xb5\x01<: python>
如何获得一个反斜杠?
谢谢
【问题讨论】:
标签: json micropython
我正在使用最新版本的 micropython。我还使用了 DS18b20 温度传感器。这些传感器的地址,例如是“b'(b\xe5V\xb5\x01<: json>
如何获得一个反斜杠?
谢谢
【问题讨论】:
标签: json micropython
您无法将bytes 与micropython 一起保存在JSON 中。就JSON 而言,这只是一些字符串。即使你得到它给你你认为你想要的东西(即单反斜杠)它仍然不会是bytes。因此,无论如何,您都面临着某种形式的转换。
一个想法是您可以将其转换为int,然后在打开它时将其转换回来。下面是一个简单的例子。当然,您不必拥有class 和staticmethods 来执行此操作。这似乎是一种将所有内容包装成一体的好方法,甚至不需要它的实例。您可以将整个class 转储到其他文件中,将import 转储到必要的文件中,然后在需要时调用它的方法。
import math, ujson, utime
class JSON(object):
@staticmethod
def convert(data:dict, convert_keys=None) -> dict:
if isinstance(convert_keys, (tuple, list)):
for key in convert_keys:
if isinstance(data[key], (bytes, bytearray)):
data[key] = int.from_bytes(data[key], 'big')
elif isinstance(data[key], int):
data[key] = data[key].to_bytes(1 if not data[key]else int(math.log(data[key], 256)) + 1, 'big')
return data
@staticmethod
def save(filename:str, data:dict, convert_keys=None) -> None:
#dump doesn't seem to like working directly with open
with open(filename, 'w') as doc:
ujson.dump(JSON.convert(data, convert_keys), doc)
@staticmethod
def open(filename:str, convert_keys=None) -> dict:
return JSON.convert(ujson.load(open(filename, 'r')), convert_keys)
#example with both styles of bytes for the sake of being thorough
json_data = dict(address=bytearray(b'\xFF\xEE\xDD\xCC'), data=b'\x00\x01\02\x03', date=utime.mktime(utime.localtime()))
keys = ['address', 'data'] #list of keys to convert to int/bytes
JSON.save('test.json', json_data, keys)
json_data = JSON.open('test.json', keys)
print(json_data) #{'date': 1621035727, 'data': b'\x00\x01\x02\x03', 'address': b'\xff\xee\xdd\xcc'}
您可能还需要注意,使用此方法您实际上从未接触过任何JSON。你输入一个dict,你得到一个dict。所有JSON 都在“幕后”进行管理。不管这一切,我会说使用struct 将是一个更好的选择。你说JSON虽然是这样,但我的回答是关于JSON。
【讨论】: