如何使用Python读取json文件夹数据? [英] How to read json folder data using Python?

查看:100
本文介绍了如何使用Python读取json文件夹数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Python 3.7.2获取json文件夹的数据.

I want to get the data of json folders using Python 3.7.2.

这是我的json文件:

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
    

  • 可以更改json文件的结构,但是它只能是一个json文件,所以我需要类似的东西:

    jdevices = getDevices(json_data)             | Output: {'device1', 'device2', 'device3'}
    

    和:

    jstatus = getStatus(json_data, "device1")    | Output: 0 
    

    推荐答案

    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']
    

    这篇关于如何使用Python读取json文件夹数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆