JanF
JanF

Reputation: 137

How to read json folder data using Python?

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:

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

Answers (3)

Debendra
Debendra

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

M.H. Tajaddini
M.H. Tajaddini

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:

  • tell python how to interact with JSON files: import json
  • load your data: data = jason.loads("path_to_file")
  • do whatever you'd want with the data, e.g. iterate over it:

for x in data: print(f"x: {x}, data[x]: {data[x]}")

Upvotes: 1

Kenan
Kenan

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

Related Questions