gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
code to extract the data from nested json file having n number of data
- User
code to extract the data from nested json file having n number of data
- Assistant
To extract data from a nested JSON file with an unknown number of data, you can use recursion. Here's an example code in Python:
def extract_data(json_data): if isinstance(json_data, dict): for key, value in json_data.items(): if isinstance(value, (dict, list)): extract_data(value) else: print(f"{key}: {value}") elif isinstance(json_data, list): for item in json_data: extract_data(item) # Example usage: json_data = { "data": [ { "id": 1, "name": "John", "details": { "age": 30, "city": "New York" } }, { "id": 2, "name": "Alice", "details": { "age": 25, "city": "London" } } ] } extract_data(json_data)This code recursively checks each key-value pair in the JSON data. If the value is a nested dictionary or a list, the function calls itself to further extract data from that nested structure. If the value is a non-nested value, it prints the key-value pair.