top | item 37416630

(no title)

peferron | 2 years ago

I haven't had a great experience dealing with JSON in Python, but maybe I'm doing it wrong. What would be the Python equivalent of this JS code?

    JSON.parse(<data>).foo?.[0]?.bar
Basically just return the `bar` field of the the first element of `foo`, or None/undefined if it doesn't exist.

discuss

order

PurpleRamen|2 years ago

Assuming <data> will be a key-value-object aka dict, it would be something like this:

    import json
    data = json.loads('<data>')
    bar = None
    if foo:=data.get('foo'):
        bar = foo[0].bar    
    print(bar)
    
If you can't be sure to get a dict, another type-check would be necessary. If you read from a file or file-like-object (like sys.stdin), json.load should be used.