Last active
September 17, 2022 10:02
-
-
Save narenaryan/124b2c03b09c4b8718cc637c5a189747 to your computer and use it in GitHub Desktop.
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
| { | |
| "languages": { | |
| "python": { | |
| "name": "Python", | |
| "author": "Guido Van Rossum", | |
| "usedFor": ["Scripting", "Web Development", "Text processing", "Data Science"] | |
| }, | |
| "go": { | |
| "name": "Go", | |
| "author": "Google", | |
| "usedFor": ["Devops Tooling", "Low-latency Servers", "command-line Tools"] | |
| } | |
| } | |
| } |
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
| import json | |
| fp = open("data.json", "r") | |
| # Custom decoder function | |
| def add_count_to_decoded_dict(obj): | |
| if "usedFor" in obj: | |
| # populate a new field `usageCount` while de-coding JSON | |
| obj["usageCount"] = len(obj["usedFor"]) | |
| return obj | |
| result = json.load(fp, object_hook=add_count_to_decoded_dict) | |
| if "languages" in result: | |
| languages = result.get("languages") | |
| if "go" in languages: | |
| golang = languages.get("go") | |
| name = golang.get("name") | |
| count = golang.get("usageCount") | |
| # Prints 'Go is mainly used for 3 reasons' | |
| print(f"{name} is mainly used for {count} reasons") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment