简体   繁体   English

在Python3中将_wmi_object序列化为JSON

[英]Serialize _wmi_object into JSON in Python3

I am having hard time with serializing _wmi_objects .我很难序列化_wmi_objects I have tried with just json.dumps() and JsonPickle library without success getting Not JSON serializable errors or with JsonPickle some unneeded fields which can't be removed and null values for every entity.Tried hardcoding every entity in a dict literal and after that json.dumps() and it dumps only the first result.我尝试仅使用json.dumps()JsonPickle库但没有成功获得Not JSON serializable错误或使用JsonPickle一些无法删除的不需要的字段以及每个实体的 null 值。尝试在 dict 文字中对每个实体进行硬编码,之后json.dumps()并且它只转储第一个结果。 Also tried making the object into a dict which had the result below.还尝试将 object 制作成具有以下结果的dict

This is what I have until now:这是我到目前为止所拥有的:

import wmi, json


def to_dict(obj):
    output ={}
    for key, item in obj.__dict__.items():
        if isinstance(item, list):
            l = []
            for item in item:
                d = to_dict(item)
                l.append(d)
            output[key] = l
        else:
            output[key] = item

    return output


c = wmi.WMI(
    computer="host",
    user="user",
    password="password"
)

for product in c.Win32_Product():
     with open('products.json','w') as fp:
         fp.write(json.dumps(to_dict(product)))

With the code above I am getting TypeError: Object of type CDispatch is not JSON serializable使用上面的代码,我得到TypeError: Object of type CDispatch is not JSON serializable

This the data that I'm getting when I print(product) :这是我print(product)时得到的数据:

instance of Win32_Product
{
        AssignmentType = 1;
        Caption = "Microsoft Visual C++ 2019 X64 Additional Runtime - 14.22.27821";
        Description = "Microsoft Visual C++ 2019 X64 Additional Runtime - 14.22.27821";
};

Since i just ran into this myself:因为我自己遇到了这个:

product is a _wmi_object containing all kind of methods, classes and properties. product是一个包含所有类型的方法、类和属性的_wmi_object

The actual data is in the property properties (which already is a dict() )实际数据在属性properties中(已经是dict()

So something like:所以像:

json.dumps(product.properties)

Cheers干杯

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

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