[Tutorial] Modifying objects built from json files (Python)

Let’s assume you’ve gotten dictionaries from json files. In this case I have two different dictionaries, but I want information reorganized. Since I’ve created two dictionary objects I can now add things to them.

This won’t affect the json files, but since they’re now pythonic objects that means I can alter them to suit my needs. In this case I want to take a list of repos from projects.json and add it to the teams.json dictionary object.

from github import Github

g = Github("token")

Creating a github object.

with open("projects.json", "r") as f:
    projects_data = json.loads(f.read())

with open("teams.json", "r") as f:
    teams_data = json.loads(f.read())

Extracting the information from the json files.

for repo_name, repo in projects_data.items():
    for team in repo['teams']:
        if "repos" not in teams_data[team]:
            teams_data[team]["repos"] = []
        teams_data[team]["repos"].append(repo_name)

So double for loops and an if statement are probably not good coding practice. It’s apparently harder for people to really parse what’s going on, but it also works so for this exercise I’m going with it.

This creates a new list that goes in each team in teams_data. This new list is made up of repos from the projects_data object.

for every repo name in the repo list in projects_data’s items (so sort of skipping the keys and going right to the items).

for every team in repo[‘teams’], there’s a ‘teams’ key in each repo and it’s linked to a list of teams. So take one of those teams and append the repo_name from earlier in the loop (if the repos key and list have not been created, create it) then add the name of the team to the list.

I’m not sure I totally follow.

So this

{
  "A-Team": {
    "members": ["auser", "buser", "cuser"]
  }
}

Becomes this:

{
  "A-Team": {
    "members": ["auser", "buser", "cuser"],
    "repos": ["ARepo", "BRepo"]
  }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s