Jump to content

Python, seaching for json data

Dujith

Atm writing a simple python script to set values in HUE lamps. Now i also want to get the values for status updates.

I have a block that gets triggered either by the menu access or each 10 seconds. 

 

Now i want to simplify 1 part and that is the way i look up groups. When i do a request i get this back as json data:

{
    "1": {
        "name": "Group 1",
        "lights": [
            "1",
            "2"
        ],
        "type": "LightGroup",
        "action": {
            "on": true,
            "bri": 254,
            "hue": 10000,
            "sat": 254,
            "effect": "none",
            "xy": [
                0.5,
                0.5
            ],
            "ct": 250,
            "alert": "select",
            "colormode": "ct"
        }
    },
    "2": {
        "name": "Group 2",
        "lights": [
            "3",
            "4",
            "5"
        ],
        "type": "LightGroup",
        "action": {
            "on": true,
            "bri": 153,
            "hue": 4345,
            "sat": 254,
            "effect": "none",
            "xy": [
                0.5,
                0.5
            ],
            "ct": 250,
            "alert": "select",
            "colormode": "ct"
        }
    }
}

The way i control light is by sending json data to an url, in my case it would be:

/api/<username>/groups/1

 

What i want to know if there is a way in python to search for "Group 2" (or whatever i call the room) and get back that it is in ID "2"

I can find enough examples how to search the otherway, but not backwards?

 

I am an complete python newbie so be gentle :D i know how to send and recieve the json data (the block already can set RGB, brightness and on and off)

 

Link to comment
Share on other sites

Link to post
Share on other sites

JSON serializes data. Most programming languages have built in functions to parse the json data and recreate the variables in it (arrays, objects, string and number variables) and then produce the JSON again.

 

See for example :

1 json — JSON encoder and decoder — Python 3.7.5rc1 documentation

2 simplejson · PyPI

 

So you can decode the JSON into an array or object, then you can use FOR or WHILE or whatever Python has to go through the information, change it as needed, and then convert the variable back to json data.

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

so you;re trying to take

/api/<username>/groups/1

 

get the number at the end and see what the name is?

 

Following the dictionary you posted you can create a function the you pass in  the dictionary and a key and then return the group name or none

from typing import Dict, Any
def get_group(res: Dict[str, Any], number: str) -> str or None:
    try:
        return res[number]["name"]
    except KeyError:
        return None


group_name = get_group(res, "1")  # Group 1
group_name = get_group(res, "2")  # Group 2
group_name = get_group(res, "3")  # None


 

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

@vorticalbox 

That json data i posted is what i get when i do a GET at 19.68.x.x/api/<username>/groups the /1 is when i know what 1 is and then set a value in it.

I have to work with Python 2 as thats the version that runs on the GIRA Homeserver.

payload=json.dumps({'xy':[x,y]})

hue_group = (self._get_input_value(self.PIN_I_GROEP))
ipadres = (self._get_input_value(self.PIN_I_IP_ADRES))
path = ('/api/apikey/groups/'+hue_group+'/action')

h = httplib.HTTPConnection(ipadres)
l = len(payload)
headers = {"Content-type": "application/json", "Content-Length": l}
h.request('PUT', path, payload, headers)

Ideally i would input the groups name in the visualisation and hue_group would be filled with the correct number.

So inputting "Group 2" would give back "2" 

Atm i fill in the number by hand. (via PIN_I_GROEP, which is an input point in the homeserver)

 

Still trying to get my head around dictionaries :S as you can see i kinda botched this together. But hey, it works!

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, Dujith said:

@vorticalbox 

That json data i posted is what i get when i do a GET at 19.68.x.x/api/<username>/groups the /1 is when i know what 1 is and then set a value in it.

I have to work with Python 2 as thats the version that runs on the GIRA Homeserver.


payload=json.dumps({'xy':[x,y]})

hue_group = (self._get_input_value(self.PIN_I_GROEP))
ipadres = (self._get_input_value(self.PIN_I_IP_ADRES))
path = ('/api/apikey/groups/'+hue_group+'/action')

h = httplib.HTTPConnection(ipadres)
l = len(payload)
headers = {"Content-type": "application/json", "Content-Length": l}
h.request('PUT', path, payload, headers)

Ideally i would input the groups name in the visualisation and hue_group would be filled with the correct number.

So inputting "Group 2" would give back "2" 

Atm i fill in the number by hand. (via PIN_I_GROEP, which is an input point in the homeserver)

 

Still trying to get my head around dictionaries :S as you can see i kinda botched this together. But hey, it works!

My function will still work in python2 if you remove the types.

 

So want it the other way? You put in a name and you get a number?

 

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

11 minutes ago, vorticalbox said:

So want it the other way? You put in a name and you get a number?

Yeah, since the api works with the number. So if i create a group in the HUE app it will get a number, i need that number for the api.

I'll get working on this and try it out.

Link to comment
Share on other sites

Link to post
Share on other sites

hue_groep_input = 'Woonkamer'


for key in r.keys():
  naam = str(r[key]['name'])
  if naam.lower() == hue_groep_input.lower():
    hue_groep_nummer = key

@vorticalbox Botched this together, had to get my head around how dictionaries worked :D in the end this is simple and works.

Now i can input the name in the visu and this will get the number back and allow me to control all the lights by making 1 logic module instead of having to make a custom one for each room. And if i ever change names or add rooms, just the input string needs to be changed.

 

Now if only they updated the Python version to 3.x on the Homeserver :S 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×