gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
python function to extract values from nested json file
- User
python function to extract values from nested json file
- Assistant
To extract values from a nested JSON file in Python, you can use recursion. Here's an example of a function that does this:
def extract_values(data, key): if isinstance(data, dict): for k, v in data.items(): if k == key: yield v elif isinstance(v, (dict, list)): yield from extract_values(v, key) elif isinstance(data, list): for item in data: yield from extract_values(item, key)Here's an example usage:
import json # Sample nested JSON data data = { "a": { "b": { "c": 1 } }, "d": [ { "e": 2 }, { "e": 3 } ] } # Convert nested JSON data to string json_str = json.dumps(data) # Load JSON string loaded_data = json.loads(json_str) # Extract values where the key is 'e' values = extract_values(loaded_data, 'e') # Print extracted values for value in values: print(value)