{{ !articles[0].partner.isSponsoringArticle ? "Platinum" : "Portal" }} Partner
python,bigdata,json,big data

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:


"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"]

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!

Published at DZone with permission of {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

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

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks