Created
March 7, 2024 01:14
-
-
Save xbalaji/0cdf1d3be2ec7b52fe178cbb96173088 to your computer and use it in GitHub Desktop.
python script to extract key, value pair from a json based using a text file with keys as filter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# filterjson.py | |
#! /usr/bin/env python3 | |
# python script to extract key, value pair from a json based using a text file with keys as filter | |
# | |
# contents.json | |
# { | |
# "031648494230": "ETUI-JNredServices-PrivateLink-Prod", | |
# "230148474224": "ETUI-JNSPlanningViewer-Test", | |
# "432541444253": "ETUI-JNCOE-Dev", | |
# "536946424273": "ETUI-JNsciences-Dev", | |
# "930848414277": "ETUI-JND-Dev" | |
# } | |
# | |
# keyfilter.txt | |
# 031648494230 | |
# 930848414277 | |
# | |
## simple shell script + jq | |
## $while IFS= read -r line; do jq -r --arg id "$line" 'to_entries | .[] | select(.key == $id)' contents.json; done < keyfilter.txt | jq -s '.|from_entries' | |
import json | |
# Read the JSON file | |
with open('contents.json', 'r') as f: | |
data = json.load(f) | |
# Read the text file | |
with open('keyfilter.txt', 'r') as f: | |
ids = [line.strip() for line in f] | |
# Get the corresponding key-value pairs | |
result = {id: data[id] for id in ids if id in data} | |
# Print the result | |
print(json.dumps(result, indent=4)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment