Mark Berube
Mark Berube

Reputation: 204

Having trouble with decoding JSON in Python

I'm a beginner when it comes to Python and I'm trying to learn how to use data structures such as JSON objects but I'm kind of stuck trying to actually get the data from the JSON object.

This is the contents example JSON data file.

{"data":{"internalName":"value","int":1}}

I'm able to print the data in the file through the code I already have, but I want to print only a certain value like the value of the internalName. How would I print this using the code I already have?

import json
json_data=open('data.txt')
data = json.load(json_data)
print json.dumps(data)
json_data.close()

Upvotes: 1

Views: 302

Answers (1)

RocketDonkey
RocketDonkey

Reputation: 37279

You can treat the resulting data structure just like a dictionary. In this case, you have have a key called data inside of the structure, and the value for that key is another dictionary, which has two keys: internalName and int. In order to access the values, you can use the syntax in the following example:

In [1]: import json

In [2]: s = '{"data":{"internalName":"value","int":1}}'

In [3]: data = json.loads(s)

In [4]: print data
{u'data': {u'int': 1, u'internalName': u'value'}}

In [5]: data['data']['internalName']
Out[5]: u'value'

So in your case, after you define data, you can access it in a similar way. Also, I would suggest using with to open the file as it will handle closing for you (when you leave the indented block):

import json

# 'with' is called a context manager, and it handles closing for you when
# you leave the indented block
with open('data.txt', 'r') as f:
    data = json.load(f)

# When the code leaves the indented block, the file is closed for you

# Print the entire structure
print json.dumps(data)

# Print out a piece of the data
print data['data']['internalName']

Upvotes: 3

Related Questions