将数据添加到JSON文件

时间:2020-09-17 01:11:26

标签: python json raspberry-pi

我正在使用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)

1 个答案:

答案 0 :(得分:1)

您可以使用json module,下面列出了一些功能,这些功能显示了对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)

确保将字典传递给store_json(),否则它将出错。

就您而言,我认为您想要:

data = {}
data["temp"] = t
data["humidity"] = h

store_json(data, "path/to/file.json")