如何使用字典中的json模块将字符串数据转换成整数?

2024-10-03 11:19:21 发布

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

我正在控制一个智能灯泡并在UI仪表板中发布它们的状态,作为一种状态,我得到了一个字符串数据“ON”和“OFF”,但是我不想得到这个字符串数据,而是想要得到一个整数数据1和0,不管怎样,我可以使用Python字典中的JSON模块将这个字符串数据转换成整数数据。你知道吗

我的智能灯泡的一些API代码如下:

 if (_deviceUrl.getcode() == 200):
     data = _deviceUrl.read().decode("utf-8")
     # Use the json module to load the string data into a dictionary
     _theJSON = json.loads(data)
     # 1. status
     devicedata['on'] = self.on_dict[_theJSON["action"]['on']]
     # 2. brightness convert to %
     devicedata["bri"] = int(round(float(_theJSON["action"]["bri"]) * 100 / 255, 0))

Tags: theto数据字符串jsondata智能on
2条回答

可以使用以下构造:

devicedata["on"] = 1 if _theJSON["action"]["on"] == "ON" else 0

这是不言自明的。你知道吗

用这样的整数替换字符串的一种方法是定义一个单独的字典:

ints = { 'OFF': 0, 'ON': 1 }

例如,如果d['action']['status']的值是字符串“ON”,那么ints[d['action']['status']]返回整数1。你知道吗

相关问题 更多 >