0

I'm trying to use a variable in my Python program and then convert it to JSON to control my smart lights. The variable "bright" is the number in JSON for the brightness of the lights. I'm not sure how to include it as it won't send unless sent as a string. My code is as follows;

import json
import requests
Light="http://192.168.1.102/api/F5La7UpN6XueJZUts1QdyBBbIU8dEvaT1EZs1Ut0/lights/5/state"
off='{"on":false}'
on='{"on":true}'
bri='{"bri":bright}'
def lights_off():
    r = requests.put(Light,off)

def lights_on():
    r = requests.put(Light,on,bright)
x=1
while x==1:
    choice=input("Lights on or off?")
    briChoice=input("What percentage brightness?")
    bright=int((briChoice/100)*254)

    if choice=="on":
         lights_on()
    elif choice=="off":
         lights_off()
    else:
        print("Don't be stupid.")


    choice2=input("Would you like to exit? Y/N").lower()
    if choice2=="y":
         break

1 Answer 1

2

The easiest way is to put a placeholder in the JSON for brightness, then insert the value of the Python variable when sending the JSON. For example:

bri = '{"bri": %s}'

Then, later:

def lights_on():
    r = requests.put(Light, on, bri % bright)

This simple solution works well when you are dealing with an integer, which doesn't need any special treatment to be used as a JSON data element. If you have a string, a Boolean, None, or a list or a dictionary, use JSON.dumps on the value before interpolating it:

"{bri: %s}" % JSON.dumps(bright)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.