python - 将数据添加到 JSON 文件
问题描述
我正在使用 python 使用 RaspberryPi。我想将数据从温度传感器发送到 JSON 文件。但是,我不知道该怎么做。我真的很感激关于这个问题的一些指导。谢谢!
这是我的代码:
import grovepi
import math
from time import sleep
from grove_rgb_lcd import *
sensor = 4
blue = 0
white = 1
setRGB(0,255,0)
while True:
try:
[temp,humidity] = grovepi.dht(sensor,blue)
if math.isnan(temp) == False and math.isnan(humidity) == False:
print("temp = %.02f C humidity =%.02f%%"%(temp, humidity))
t = str(temp)
h = str(humidity)
setText("Temp:" + t + "C\n" + "Humidity :" + h + "%")
except (IOError, TypeError) as e:
print(str(e))
setText("")
except KeyboardInterrupt as e:
print(str(e))
setText("")
break
sleep(0.05)
解决方案
您可以为此使用json 模块,我在下面列出了显示读取和写入 JSON 文件的函数:
import json
def read_json(file_path:str) -> dict:
"""Takes in a json file path and returns it's contents"""
with open(file_path, "r") as json_file:
content = json.load(json_file)
return content
def store_json(data:dict, file_path:str):
"""Takes in a python dict and stores it as a .json file"""
with open(file_path, "w") as json_file:
json.dump(data, json_file)
确保将 dict 传递给store_json()
,否则会出错。
在你的情况下,我认为你想要:
data = {}
data["temp"] = t
data["humidity"] = h
store_json(data, "path/to/file.json")
推荐阅读
- postgresql - Indexing a jsonb array in Postgres
- java - 如何创建从内存到数据库的后写缓存?
- c# - Avoid OnResultExecuted Filter on ASP.NET MVC 5 application's Action
- python - 创建上下文后获取python守护进程pid
- ruby-on-rails - Rails 上的 select_tag 中的 ArgumentError
- vba - 处理项目后重新选择日历中的项目
- python - 将 websocket 用于 python 网络爬虫——rsv 尚未实现
- php - OVH CRON:如何执行 Symfony 命令?
- typescript - Typescript extensions. Conditional Types
- linux - 在记录过程运行时清除日志文件