Skip to content

Instantly share code, notes, and snippets.

@ajkerrigan
Last active November 3, 2022 12:02
Show Gist options
  • Save ajkerrigan/6b202df6da681aa229783cafdebaadab to your computer and use it in GitHub Desktop.
Save ajkerrigan/6b202df6da681aa229783cafdebaadab to your computer and use it in GitHub Desktop.
Restructuring GitHub GraphQL responses with Glom
from glom import glom, Coalesce, Val
from rich.pretty import pprint
nodes = [
{
"owner": {"login": "python"},
"name": "cpython",
"stargazerCount": 48591,
"createdAt": "2017-02-10T19:23:51Z",
"updatedAt": "2022-11-03T04:49:20Z",
"defaultBranchRef": {
"name": "main",
"target": {"history": {"totalCount": 115096}},
},
},
{
"owner": {"login": "aosp-mirror"},
"name": "kernel_common",
"stargazerCount": 435,
"createdAt": "2008-10-21T18:19:54Z",
"updatedAt": "2022-10-30T10:39:56Z",
"defaultBranchRef": None,
},
]
spec = [
{
"owner": "owner.login",
"repo": "name",
"stars": "stargazerCount",
"created": "createdAt",
"updated": "updatedAt",
"commits": Coalesce("defaultBranchRef.target.history.totalCount", Val(None)),
}
]
print("Original node data:")
pprint(nodes, indent_guides=False, expand_all=True)
print("\nRestructured with glom:")
pprint(glom(nodes, spec), indent_guides=False, expand_all=True)
[
{
'owner': 'python',
'repo': 'cpython',
'stars': 48591,
'created': '2017-02-10T19:23:51Z',
'updated': '2022-11-03T04:49:20Z',
'commits': 115096
},
{
'owner': 'aosp-mirror',
'repo': 'kernel_common',
'stars': 435,
'created': '2008-10-21T18:19:54Z',
'updated': '2022-10-30T10:39:56Z',
'commits': None
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment