import json | |
def filter_by_category(input_file, output_file, target_category): | |
# Read the input JSON file | |
with open(input_file, 'r') as f: | |
data = json.load(f) | |
# Filter the entries where the second element of category_hierarchy is "Olympics" | |
filtered_data = [ | |
entry for entry in data | |
if len(entry.get('category_hierarchy', [])) > 1 and entry['category_hierarchy'][1] in target_category | |
] | |
# Write the filtered entries to a new JSON file | |
with open(output_file, 'w') as f: | |
json.dump(filtered_data, f, indent=4) | |
# Usage | |
input_file = '/home/yiyangai/stephenqs/datasets/wikihow/Arts and Entertainment.json' # Replace with your input file name | |
output_file = 'filtered_output.json' # Replace with your desired output file name | |
target_category = ['Banks and Financial Institutions','Government','Investments and Trading','Legal Matters','Marketing','Real Estate','Sharing Economy'] | |
filter_by_category(input_file, output_file, target_category) | |