Unexpected token when trying to convert to JSON

Hello, I am switching to Adafruit's python library because pimoroni did not include a sea level/altitude parameter. For some reason, I cannot convert the output to a JSON object. What am I missing?


# SPDX-License-Identifier: MIT

import time
import board
import adafruit_bme680

# Create sensor object, communicating over the board's default I2C bus
i2c = board.I2C()  # uses board.SCL and board.SDA
bme680 = adafruit_bme680.Adafruit_BME680_I2C(i2c, debug=False)

# change this to match the location's pressure (hPa) at sea level
bme680.sea_level_pressure = 1013.25

# You will usually have to add an offset to account for the temperature of
# the sensor. This is usually around 5 degrees but varies by use. Use a
# separate temperature sensor to calibrate this one.
temperature_offset = -5

while True:
    print("\nTemperature: %0.1f C" % (bme680.temperature + temperature_offset))
    print("Gas: %d ohm" % bme680.gas)
    print("Humidity: %0.1f %%" % bme680.relative_humidity)
    print("Pressure: %0.3f hPa" % bme680.pressure)
    print("Altitude = %0.2f meters" % bme680.altitude)


The output you are generating is a string, not json.

Could you try something like:

import json


"Temperature": %0.1f C" % (bme680.temperature + temperature_offset),
"Gas: %d ohm" % bme680.gas,
"Humidity: %0.1f %%" % bme680.relative_humidity,
"Pressure: %0.3f hPa" % bme680.pressure,
"Altitude: %0.2f meters" % bme680.altitude

returns syntax error:

I forgot some quotes and it probably needs to all be on the same line, not sure how python interpretes it.

print(json.dumps({"Temperature": "%0.1f C" % (bme680.temperature + temperature_offset),"Gas": "%d ohm" % bme680.gas,"Humidity": "%0.1f %%" % bme680.relative_humidity,"Pressure": "%0.3f hPa" % bme680.pressure,"Altitude": "%0.2f meters" % bme680.altitude}))

Also not sure how the printf formatting is being interpreted inside json.dump, probably need to set variables first.

Here is a link to an explanation of using Json in python that might help you


This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.