[b]"Best way to JSON Python get all values for key? Need help!"[/b] or [b]"How to JSON Python get all values for k

18 Replies, 1100 Views

Ugh, nested JSON is the worst. I feel your pain!

For a quick fix, try this recursive function:
```python
def get_values(obj, key):
if isinstance(obj, dict):
for k, v in obj.items():
if k == key:
yield v
yield from get_values(v, key)
elif isinstance(obj, list):
for item in obj:
yield from get_values(item, key)
```
Call it with `list(get_values(data, 'a'))`. Works like a charm!

Messages In This Thread



Users browsing this thread: 1 Guest(s)