Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Python Python compiling error (Python Beginner)

stevan

New Coder
I'm trying to get data from my temperature and humidity sensor and write the data to a JSON file every minute. I started learning Python two days ago, so I have no idea why these errors occur (the output is in the attachment):


The Code:
Python:
import time
import board
import adafruit_dht
import psutil
import io
import json
import os
from datetime import date
from datetime import datetime

# We first check if a libgpiod process is running. If yes, we kill it!
for proc in psutil.process_iter():
    if proc.name() == "libgpiod_pulsein" or proc.name() == "libgpiod_pulsei":
        proc.kill()
sensor = adafruit_dht.DHT11(board.D23)

# init
temp_values = [10]
hum_values = [10]
counter = 0

#check if file is there
def startupCheck():
    if os.path.isfile("data.json") and os.access("data.json", os.R_OK):
        # checks if file exists
        print("File exists and is readable")
    else:
        print("Either file is missing or is not readable, creating file...")
        # craete json file
        with open("data.json", "w"):
            print("The json file is created.")


def calc_avgValue(values):
    sum = 0
    for iterator in values:
        sum = sum + iterator
    return sum / len(values)


startupCheck()

while True:
    try:
        #insert values in array
        temp_values.insert(counter, sensor.temperature)
        hum_values.insert(counter, sensor.humidity)
        
        
        counter = counter + 1
        time.sleep(0.2)
        
        if counter >= 10:
            print(
                "Temperature: {}*C   Humidity: {}% ".format(
                    round(calc_avgValue(temp_values), 2),
                    round(calc_avgValue(hum_values), 2),
                )
            )
            print("Error occured in line 58")
            # get time
            today = date.today()
            now = datetime.now()
            print("Error occured in line 63")
            # init json object
            data = {
                "temperature": round(calc_avgValue(temp_values), 2),
                "humidity": round(calc_avgValue(hum_values), 2),
                "fullDate": today,
                "fullDate2": today.strftime("%d/%m/%Y"),
                "fullDate3": today.strftime("%B %d, %Y"),
                "fullDate4": today.strftime("%b-%d-%Y"),
                "date_time": now.strftime("%d/%m/%Y %H:%M:%S"),
            }
            print("Error occured in line 74")
            json_object = json.dumps(data, indent = 4)
            print(json_object)

            with open("data.json", "w") as outfile:
                outfile.write(json_object)

            counter = 0
    except RuntimeError as error:
        continue
    except Exception as error:
        sensor.exit()
        raise error("I occured randomly because I'm gay")
    time.sleep(0.2)
 

Attachments

  • Screenshot 2022-07-05 232138.png
    Screenshot 2022-07-05 232138.png
    107.2 KB · Views: 5
i forgot to delete the () after the raise error (next to the last line). That should cause an error which is not the problem. just imagine the code without the ("....").
Error without the (''...'') in the attachment
 

Attachments

  • Screenshot 2022-07-05 233429.png
    Screenshot 2022-07-05 233429.png
    158.7 KB · Views: 5
Your error seems to indicate that your data variable has not been properly defined as a JSON string. Looking at your code it does in fact appear to be an invalid JSON string as you have an extra , at the end.

Try to delete the last , in this data

Python:
data = {
                "temperature": round(calc_avgValue(temp_values), 2),
                "humidity": round(calc_avgValue(hum_values), 2),
                "fullDate": today,
                "fullDate2": today.strftime("%d/%m/%Y"),
                "fullDate3": today.strftime("%B %d, %Y"),
                "fullDate4": today.strftime("%b-%d-%Y"),
                "date_time": now.strftime("%d/%m/%Y %H:%M:%S")
            }
 
I think you have got the value to insert and the index to insert args for the `.insert` function the wrong way round. Anyway, I switched to `.append` for simplicity. Try this code.
Python:
import time
import board
import adafruit_dht
import psutil
import io
import json
import os
from datetime import date
from datetime import datetime

# We first check if a libgpiod process is running. If yes, we kill it!
for proc in psutil.process_iter():
    if proc.name() == "libgpiod_pulsein" or proc.name() == "libgpiod_pulsei":
        proc.kill()
sensor = adafruit_dht.DHT11(board.D23)

# init
temp_values = [10]
hum_values = [10]
counter = 0

#check if file is there
def startupCheck():
    if os.path.isfile("data.json") and os.access("data.json", os.R_OK):
        # checks if file exists
        print("File exists and is readable")
    else:
        print("Either file is missing or is not readable, creating file...")
        # craete json file
        with open("data.json", "w") as f:
            print("The json file is created.")


def calc_avgValue(values):
    sum = 0
    for iterator in values:
        sum += iterator
    return sum / len(values)


startupCheck()

while True:
    try:
        #insert values in array
        temp_values.append(sensor.temperature)
        hum_values.append(sensor.humidity)
       
       
        counter += 1
        time.sleep(0.2)
       
        if counter >= 10:
            print(
                "Temperature: {}*C   Humidity: {}% ".format(
                    round(calc_avgValue(temp_values), 2),
                    round(calc_avgValue(hum_values), 2),
                )
            )
            print("Error occured in line 58")
            # get time
            today = date.today()
            now = datetime.now()
            print("Error occured in line 63")
            # init json object
            data = {
                "temperature": round(calc_avgValue(temp_values), 2),
                "humidity": round(calc_avgValue(hum_values), 2),
                "fullDate": today,
                "fullDate2": today.strftime("%d/%m/%Y"),
                "fullDate3": today.strftime("%B %d, %Y"),
                "fullDate4": today.strftime("%b-%d-%Y"),
                "date_time": now.strftime("%d/%m/%Y %H:%M:%S"),
            }
            print("Error occured in line 74")
            json_object = json.dumps(data, indent = 4)
            print(json_object)

            with open("data.json", "w") as outfile:
                outfile.write(json_object)

            counter = 0
    except RuntimeError as error:
        continue
    except Exception as error:
        sensor.exit()
        raise error("I occured randomly because I'm gay")
    time.sleep(0.2)
 
I don't know about the suggestions by Coding4Fun and Diddly, but I found the solution to be real easy : just add default=str to your json_dumps call:

Python:
json_object = json.dumps(data, indent = 4, default=str)

This gets rid of the errormessage and gives you the json_object.
I found this by Googling the errormessage and opening the second hit 😉
 
@cbreemer I was talking about the first error. In terms of the second error, it occurs because a datetime object can't be converted to a string. Your solution works because the json dumps function calls the string function on the datetime object since it can't serialise it itself.
 
@cbreemer I was talking about the first error. In terms of the second error, it occurs because a datetime object can't be converted to a string. Your solution works because the json dumps function calls the string function on the datetime object since it can't serialise it itself.
Oh ok, I didn't realize that. I thought that the first error has been superseded by the second.
I do wonder though WHY a datetime object can't be serialized ...
 
It can't be serialised by the json dumps func since it doesn't know how to handle that type of class. The str function does though.
Yes, that's what it says - or at least implies. The reason WHY is probably because it does not want to make assumptions about the localized format of the date/time.
 
Back
Top Bottom