Skip to content

Instantly share code, notes, and snippets.

@narenaryan
Last active September 17, 2022 10:02
Show Gist options
  • Select an option

  • Save narenaryan/124b2c03b09c4b8718cc637c5a189747 to your computer and use it in GitHub Desktop.

Select an option

Save narenaryan/124b2c03b09c4b8718cc637c5a189747 to your computer and use it in GitHub Desktop.
{
"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"]
}
}
}
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