简体   繁体   English

如何以像 kotlin 这样简单而富有表现力的方式访问深度嵌套且不可靠的 json 值?

[英]How can I access deeply nested and unreliable json values in a simple and expressive way like kotlin?

I am trying to get this attribute which is very deeply nested.我试图获得这个嵌套非常深的属性。

The problem is that some of the values on the way tends to be None .问题是途中的一些值往往是None

here is how I did it (the wrong way).这是我的做法(错误的方式)。

def name(x):
    x = x["relay_rendering_strategy"]
    if x:
        x = x["view_model"]
        if x:
            x = x["profile"]
            if x:
                x = x["event_place"]
                if x:
                    x = x["contextual_name"]
                    if x:
                        return x.lower()
    return ''
data = [x for x in get_events() if name(x) == 'ved siden af']

In kotlin there is a nice syntax like this:在 kotlin 中有这样一个很好的语法:

val name = first?.second?.third?.andSoFourth ?: ''

Is there a similar awesome way you can do it in python???有没有类似的很棒的方法可以在 python 中做到?

You can do something similar with dict.get and default values:您可以使用dict.get和默认值执行类似的操作:

def name(x):
    return x.get("relay_rendering_strategy", {}).get("view_model", {}).get("profile", {}).get("event_place", {}).get("contextual_name", "").lower()

Or use a simple try-except:或者使用一个简单的try-except:

def name(x):
    try:
        return x["relay_rendering_strategy"]["view_model"]["profile"]["event_place"]["contextual_name"].lower()
    except KeyError:
        return ""

Or simply keep the nesting level down with a loop to be more DRY:或者简单地通过循环保持嵌套级别更干燥:

def name(x):
    for k in ("relay_rendering_strategy","view_model","profile","event_place","contextual_name"):
        if k not in x:
            return ""
        x = x[k]
    return x.lower()

In python, it is better to ask forgiveness than permission.在 python 中,请求宽恕比许可好。

Using try/except (as suggested by @Iain Shelvington).使用 try/except(如@Iain Shelvington 所建议)。

def name(x):
    try:
        return x["relay_rendering_strategy"]["view_model"]["profile"]["event_place"]["contextual_name"].lower()
    except (KeyError, AttributeError):
        return ""

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

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