Created
December 14, 2017 13:24
-
-
Save raganmd/e6cd2eb5f1874d19f99a259d7b800f37 to your computer and use it in GitHub Desktop.
JSON, as a format is very similar to python dictionaries, so similar in fact there's a very simple way to work with it. If you're already working with dictionaries this will feel like an easy transition. There are, however, a few things you need to keep in mind. We need to make sure that our JSON is correctly formatted. If you compare the in our…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# First we need to import the json module. | |
import json | |
# next we're going to use just the text from our text dat | |
imported_dict = op( 'text_simple_json' ).text | |
# next we'll use json.loads to import that as a python dictionary | |
dict_from_json = json.loads( imported_dict ) | |
# first let's just print the dictionary to make sure things worked out | |
print( "Here is our whole json object" ) | |
print( imported_dict ) | |
print( '_ ' * 10 ) | |
# next we could print just the top tier keys | |
print( "Here are our top tier keys" ) | |
for item in dict_from_json.keys(): | |
print( item ) | |
print( '\n' ) | |
print( '_ ' * 10 ) | |
# next let's print the keys in our 'inventory' dictionary | |
print( "Here are the keys in inventory" ) | |
for item in dict_from_json[ 'inventory' ].keys(): | |
print( item ) | |
print( '\n' ) | |
print( '_ ' * 10 ) | |
# since we're on a roll, let's first print our keys, and | |
# then print their values | |
print( "Here are the keys and values in inventory" ) | |
for key, value in dict_from_json[ 'inventory' ].items(): | |
print( key, 'contains', value ) | |
print( '\n' ) | |
print( '_ ' * 10 ) | |
# That's still not very pretty, so let's see if we can make | |
# something that's a little nicer | |
print( "Pretty printing our keys and values" ) | |
for key, value in dict_from_json[ 'inventory' ].items(): | |
print( key, 'contains' ) | |
for item, quantity in value.items(): | |
print( quantity, item ) | |
print( '\n' ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment