Skip to content

Instantly share code, notes, and snippets.

@ducnh1022
Created June 14, 2024 09:35
Show Gist options
  • Save ducnh1022/0e68e949fb0e86a14de5d2e036676091 to your computer and use it in GitHub Desktop.
Save ducnh1022/0e68e949fb0e86a14de5d2e036676091 to your computer and use it in GitHub Desktop.
jsontagdnh1022
import json
def search_json(data, target_tag):
"""
Recursively search for a tag in a JSON object and return a list of values associated with that tag.
:param data: The JSON object (dictionary or list) to search in.
:param target_tag: The tag to search for.
:return: A list of values associated with the target tag.
"""
results = []
if isinstance(data, dict):
for key, value in data.items():
if key == target_tag:
results.append(value)
results.extend(search_json(value, target_tag))
elif isinstance(data, list):
for item in data:
results.extend(search_json(item, target_tag))
return results
# Example usage:
# Assuming you have a JSON file named 'data.json'
# Load JSON data from a file
with open('data.json', 'r') as file:
json_data = json.load(file)
# Search for a specific tag in the JSON data
tag_to_search = 'desired_tag'
found_values = search_json(json_data, tag_to_search)
print(f"Values associated with tag '{tag_to_search}': {found_values}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment