简体   繁体   English

将 JSON 文件转换为 Python 对象

[英]Converting a JSON file into Python Objects

I have a JSON file which I want to take and put into python objects.我有一个 JSON 文件,我想将其放入 python 对象中。 It has two parts, staff and assets and I want to load them into two separate ones.它有两个部分,员工和资产,我想将它们加载到两个独立的部分中。 Here is a sample of the JSON file:这是 JSON 文件的示例:

{
"staff": [
    {
        "id": "DA7153",
        "name": [
            "Fran\u00c3\u00a7ois",
            "Ullman"
        ],
        "department": {
            "name": "Admin"
        },
        "server_admin": "true"
    },
    {
        "id": "DA7356",
        "name": [
            "Bob",
            "Johnson"
        ],
        "department": {
            "name": "Admin"
        },
        "server_admin": "false"
    },
],
"assets": [
    {
        "asset_name": "ENGAGED SLOTH",
        "asset_type": "File",
        "owner": "DA8333",
        "details": {
            "security": {
                "cia": [
                    "HIGH",
                    "INTERMEDIATE",
                    "LOW"
                ],
                "data_categories": {
                    "Personal": "true",
                    "Personal Sensitive": "true",
                    "Customer Sensitive": "true"
                }
            },
            "retention": 2
        },
        "file_type": "Document",
        "server": {
            "server_name": "ISOLATED UGUISU",
            "ip": [
                10,
                234,
                148,
                52
            ]
        }
    },
    {
        "asset_name": "ISOLATED VIPER",
        "asset_type": "File",
        "owner": "DA8262",
        "details": {
            "security": {
                "cia": [
                    "LOW",
                    "HIGH",
                    "LOW"
                ],
                "data_categories": {
                    "Personal": "false",
                    "Personal Sensitive": "false",
                    "Customer Sensitive": "true"
                }
            },
            "retention": 2
        },
    },
]

I have tried to create a class for staff but whenever I do I get the error "TypeError: dict expected at most 1 argument, got 3"我试图为员工创建一个类,但每当我这样做时,我都会收到错误“TypeError:dict 最多需要 1 个参数,得到 3”

The code I am using looks like this:我正在使用的代码如下所示:

import json

with open('Admin_sample.json') as f:
    admin_json = json.load(f)

class staffmem(admin_json):
    def __init__(self, id, name, department, server_admin):
        self.id = id
        self.name = name
        self.deparment = department[name]
        self.server_admin = server_admin

    def staffid(self):
        return self.id

print(staffmem.staffid)

I just can't work it out.我就是搞不定。 Any help would be appreciated.任何帮助,将不胜感激。

Thanks.谢谢。

The following should be a good starting point but you have to fix few things.以下应该是一个很好的起点,但您必须解决一些问题。 Note that I am using get() everywhere to provide a "safe" default if the keys do not exist:请注意,如果密钥不存在,我会在任何地方使用get()来提供“安全”默认值:

import json

class StaffMember:
    def __init__(self, json_entry):
        self.name = ",".join(json_entry.get("name"))
        self.id = json_entry.get("id")
        self.dept = json_entry.get("department", {}).get("name")
        self.server_admin = (
            True
            if json_entry.get("server_admin", "false").lower() == "true"
            else False
        )

# Get the data
with open("/tmp/test.data") as f:
    data = json.load(f)

# For every entry in the data["staff"] create object and index them by ID
all_staff = {}
for json_entry in data.get("staff", []):
    tmp = StaffMember(json_entry)
    all_staff[tmp.id] = tmp


print(all_staff)
print(all_staff['DA7153'].name)

Output:输出:

$ python3 /tmp/test.py
{'DA7153': <__main__.StaffMember object at 0x1097b2d50>, 'DA7356': <__main__.StaffMember object at 0x1097b2d90>}
François,Ullman

Potential Improvements:潜在的改进:

  • Unicode handling Unicode 处理
  • Add getters/setters添加 getter/setter
  • Instead of passing json dict in ctor, consider adding a from_json() static method to create your object考虑添加一个from_json()静态方法来创建您的对象,而不是在 ctor 中传递 json dict
  • Error handling on missing values缺失值的错误处理
  • Consider using a dataclass in py3 if this object is used to only/mainly store data如果此对象仅/主要用于存储数据,请考虑在 py3 中使用数据类
  • Consider the namedtuple approach from the comments if you do not intend to modify the object (read-only)如果您不打算修改对象(只读),请考虑注释中的 namedtuple 方法

Notes:笔记:

  • The json you provided is not correct - you will need to fix it您提供的 json 不正确 - 您需要修复它
  • Your syntax is wrong in your example and the naming convention is not much pythonic (read more here您的示例中的语法是错误的,并且命名约定不是很pythonic(在此处阅读更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM