Best way to JSON Python get all values for key? Need help! or How to JSON Python get all values for k

18 Replies, 1219 Views

For a no-library solution, this works:

```python
def extract_values(obj, key):
arr = []
if isinstance(obj, dict):
for k, v in obj.items():
if k == key:
arr.append(v)
arr.extend(extract_values(v, key))
elif isinstance(obj, list):
for item in obj:
arr.extend(extract_values(item, key))
return arr
```
Call it with `extract_values(data, 'a')`. Simple and effective.

Messages In This Thread



Users browsing this thread: 1 Guest(s)