· python json

Python: Reading a JSON file

I've been playing around with some code to spin up AWS instances using Fabric and Boto and one thing that I wanted to do was define a bunch of default properties in a JSON file and then load this into a script.

I found it harder to work out how to do this than I expected to so I thought I'd document it for future me!

My JSON file looks like this:

config/defaults.json


{
	"region" : "eu-west-1",
	"instanceType": "m1.small"
}

To read that file we can do the following:


>>> open('config/defaults.json').read()
'{\n\t"region" : "eu-west-1",\n\t"instanceType": "m1.small"\n}'

We can then use the json.loads function to convert that from a string into a Python object:


>>> import json
>>> config = json.loads(open('config/defaults.json').read())
>>> config
{u'region': u'eu-west-1', u'instanceType': u'm1.small'}

We'd write the following code to get the region:


>>> config["region"]
u'eu-west-1'

I guess we might want to use a different approach that didn't load the whole string into memory if we had a large JSON file but for my purposes this will do!

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket