write a python code to flatten json list of dict
- User
write a python code to flatten json list of dict
- Assistant
def flatten_json(json_list): flattened_list = [] for item in json_list: flattened_dict = {} for key, value in item.items(): if isinstance(value, dict): for nested_key, nested_value in value.items(): flattened_dict[key + '_' + nested_key] = nested_value else: flattened_dict[key] = value flattened_list.append(flattened_dict) return flattened_list
- User
write a python code to flatten this json data
[ { "name": "John", "age": 30, "address": { "street": "123 Main St", "city": "New York" }, "hobbies": ["reading", "gaming"] }, { "name": "Jane", "age": 25, "address": { "street": "456 Elm St", "city": "Los Angeles" }, "hobbies": ["cooking", "painting"] } ]
- Assistant
import json
data = [ { "name": "John", "age": 30, "address": { "street": "123 Main St", "city": "New York" }, "hobbies": ["reading", "gaming"] }, { "name": "Jane", "age": 25, "address": { "street": "456 Elm St", "city": "Los Angeles" }, "hobbies": ["cooking", "painting"] } ]
def flatten_json(json_list): flattened_list = [] for item in json_list: flattened_dict = {} for key, value in item.items(): if isinstance(value, dict): for nested_key, nested_value in value.items(): flattened_dict[key + '_' + nested_key] = nested_value elif isinstance(value, list): flattened_dict[key] = ', '.join(value) else: flattened_dict[key] = value flattened_list.append(flattened_dict) return flattened_list
flattened_data = flatten_json(data)
output = json.dumps(flattened_data, indent=4) print(output)
- User
now exclude address and hobbies and return in dict
- Assistant
import json
data = [ { "name": "John", "age": 30, "address": { "street": "123 Main St", "city": "New York" }, "hobbies": ["reading", "gaming"] }, { "name": "Jane", "age": 25, "address": { "street": "456 Elm St", "city": "Los Angeles" }, "hobbies": ["cooking", "painting"] } ]
def flatten_json(json_list): flattened_list = [] for item in json_list: flattened_dict = {} for key, value in item.items(): if key not in ["address", "hobbies"]: flattened_dict[key] = value flattened_list.append(flattened_dict) return flattened_list
flattened_data = flatten_json(data)
output = json.dumps(flattened_data, indent=4) print(output)