1

I am trying to build an IOT setup. I am thinking of using a json file to store states of the sensors and lights of the setup.

I have created a function to test out my concept. Here is what I wrote so far for the data side of things.

            {
                "sensor_data": [
                    {
                        "sensor_id": "302CEM/lion/light1",
                        "sensor_state": "on"
                    },
                    {
                        "sensor_id": "302CEM/lion/light2",
                        "sensor_state": "off"
                    }
                ]
            }

            def read_from_db():
                with open('datajson.json') as f:
                    data = json.load(f)

                for sensors in data['sensor_data']:
                    name = sensors['sensor_id']



            read_from_db()

What I want to do is to parse the sensor_id into an array so that I can access them by saying for example sensor_name[0]. I am not sure how to go about it. I tried array.array but it doesn't save any values, have also tried .append but not the result I expected. Any suggestions?

1 Answer 1

2

If I understood correctly, all you have to do is assign all those sensors to names using a for loop and then return the result:

import json

def read_from_db():
    with open('sensor_data.json') as f:
        data = json.load(f)
        names = [sensors['sensor_id'] for sensors in data['sensor_data']]
        return names

sensor_names = read_from_db()
for i in range(len(sensor_names)):
    print(sensor_names[i])

This will print:

302CEM/lion/light1
302CEM/lion/light2
Sign up to request clarification or add additional context in comments.

3 Comments

thank you so much that works perfectly but I had a question. what is the difference between names = [sensors['sensor_id'] for sensors in data['sensor_data']] and for sensors in data['sensor_data']: names = [[sensors['sensor_id']]
The first is list comprehension, a feature of Python that allows you to create lists using one-liners. names = [[sensors['sensor_id']] does not create the desired list because you're not appending the new elements to that list and you only assign the element you're iterating over each time. It should be: names.append(sensors['sensor_id']).
Really appreciate this mate

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.