[Tutorial] Reading a json file

I was struggling with formatting issues earlier so I thought I’d revisit some of the things I went over.

Say we had a json file that was formatted to be a python dictionary. Some important differences are the use of double quotes (“”) as opposed to (”). Another difference is the lack of a trailing comma. So in python when you’re making a list you can do A, B, C, D, and that’s alright. However you can’t leave that trailing comma in json files. Note: there are also json validators out there.

{
  "apps-mauler": {
    "repos": "testproject1",
    "teams": ["A-Team","B-Team", "C-Team"]
  },

  "apps-plasma": {
    "repos": "testproject2",
    "teams": ["A-Team"]
  },

  "apps-phaser": {
    "repos": "testproject3",
    "teams": ["B-Team", "C-Team"]
  }
}

So let’s call this file projects.json.

How do we turn this into an actual python dictionary?

import json

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

projects_data is now a python object (dictionary) that we can manipulate just like a dictionary. It’s easy!

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