Over a million developers have joined DZone.
Platinum Partner

Python: Reading a JSON file

· Big Data Zone

The Big Data Zone is presented by Exaptive.  Learn how rapid data application development can address the data science shortage.

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!

The Big Data Zone is presented by Exaptive.  Learn about how to rapidly iterate data applications, while reusing existing code and leveraging open source technologies.

Topics:
python,bigdata,json,big data

Published at DZone with permission of Mark Needham , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}