首页 > 解决方案 > 将数据添加到 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)

标签: pythonjsonraspberry-pi

解决方案


您可以为此使用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")

推荐阅读