Reputation: 137
I want to get the data of json folders using Python 3.7.2.
This is my json file:
{"device":
[
{"name": "device1", "status": 0},
{"name": "device2", "status": 1},
{"name": "device2", "status": 1}
]
}
For my project I need following variables:
variable of all devices gathered in a list:
devices = ["device1", "device1", "device1"]
status of devices saved in different variables:
status_device1 = 0
status_device2 = 1
status_device3 = 1
It is possible to change the structure of the json file, but it has to be only one json file, so I need something like:
jdevices = getDevices(json_data) | Output: {'device1', 'device2', 'device3'}
and:
jstatus = getStatus(json_data, "device1") | Output: 0
Upvotes: 0
Views: 207
Reputation: 1142
import json
class DeviceHelper:
def __init__(self, json_file):
"""open json file and load json content"""
with open(json_file, 'rb') as file:
self.device_info = json.load(file)
def get_device_status(self, name):
"""loop over the divices list and compare"""
for device in self.device_info.get('device'):
if device.get('name') == name:
return device.get('status')
return 'Lol no device found'
def get_devices(self):
return [device.get('name') for device in self.device_info.get('device')]
# path to json file
device_info = DeviceHelper('devices.json')
device_info.get_device_status('device2')
>>> 1
device_info.get_devices()
>>> ['device1', 'device2', 'device2']
Upvotes: 2
Reputation: 820
python has built-in support for JSON files, and it also has a very handy data structure named dictionary which works brilliantly with JSON.
You'll basically need to do this:
import json
data = jason.loads("path_to_file")
for x in data:
print(f"x: {x}, data[x]: {data[x]}")
Upvotes: 1
Reputation: 14104
You can do this in pandas
import pandas as pd
jsn = {"device": [
{"name": "device1", "status": 0},
{"name": "device2", "status": 1},
{"name": "device2", "status": 1}]}
df = pd.DataFrame(jsn['device'])
name status
0 device1 0
1 device2 1
2 device2 1
devices = df['name'].tolist()
status = df['status'].tolist()
Upvotes: 0