简体   繁体   English

如何自动提取嵌套的 json,其中很少有 json 对象嵌套 json 对象,但可以用 __dict__ 解析

[英]How to auto extracting nested json in which few json object nested json object but can be parsed with __dict__

object looks like as below对象如下所示


{
"id":1,
"image":"path/to/image",
"employee_data":<sql_alcahmy_object>,
}

again sql_alcahmy_object is as below再次 sql_alcahmy_object 如下

{
"employee_previous":<sql_alchemy_object2>,
"employee_salary":"1$",

}

again sql_alcahmy_object2 is as below再次 sql_alcahmy_object2 如下


{"company":"xyz","years":10}

below method will be used to extract all data from sql alchemy object下面的方法将用于从 sql alchemy 对象中提取所有数据

sql_alchemy_object.__dict__

below is the recursive method planned but it didn't work out下面是计划中的递归方法,但没有成功

def extract_recursive(deepvalue,alldata={}):
    for eachkey,eachvalue in deepvalue.__dict__.iteritems():
        if hasattr(eachvalue,"__dict__"):
            alldata.update({eachkey:extract_recursive(eachvalue)})
        else:   
            alldata.update({eachkey:eachvalue})
    print(alldata)

expected output预期产出


{
"id":1,
"image":"path/to/image",
"employee_data":{
             "employee_previous":{"company":"xyz","years":10},
             "employee_salary":"1$",

              }
}

Available methods in deepvalue and sql_alcahmy_object as below deepvalue 和 sql_alcahmy_object 中的可用方法如下

 ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__mapper__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__table__', '__tablename__', '__weakref__', '_decl_class_registry', '_sa_class_manager', 'age'] 

There is a misunderstanding of what is __dict__ here这里对什么是__dict__存在误解

It actually is它实际上是

A dictionary or other mapping object used to store an object's (writable) attributes.用于存储对象(可写)属性的字典或其他映射对象。

but it does not allow to access nested dicts of a dict.但它不允许访问字典的嵌套字典。

So, if you want to iterate over items in a dict, you just have to call thedict.iteritems() not thedict.__dict__.iteritems() .所以,如果你想遍历 dict 中的项目,你只需要调用thedict.iteritems()而不是thedict.__dict__.iteritems()

Then, if you want to check if variable contains a dict instance, use isinstance(a_dict, dict) , not hasattr(a_dict, '__dict__') .然后,如果要检查变量是否包含dict实例,请使用isinstance(a_dict, dict) ,而不是hasattr(a_dict, '__dict__')

Additionaly, using a mutable object as a default value for a function argument can produce non-intuitive result and is strongly discouraged (see "Least Astonishment" and the Mutable Default Argument ) Instead you should probably pass None as default value and add a alldata = alldata or {} at the begining of your function.此外,使用可变对象作为函数参数的默认值会产生不直观的结果,强烈建议不要使用(请参阅“最小惊讶”和可变默认参数)相反,您应该将None作为默认值并添加一个alldata = alldata or {}在您的函数的开头。

Finally, although I do not understand the point of your function, this version should work better:最后,虽然我不明白你的功能点,但这个版本应该更好用:

def extract_recursive(deepvalue, alldata=None):
    alldata = alldata or {}
    for eachkey, eachvalue in deepvalue.iteritems():
        if isinstance(eachvalue, dict):
            alldata.update({eachkey:extract_recursive(eachvalue)})
        else:
            alldata.update({eachkey:eachvalue})
    print(alldata)

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

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