# File: json-ex.py # Program to read in JSON data, # parse it, and print it out in # several ways; also, how to access it # # Matt Bishop, MHI 289I, Winter 2019 # JSON module import json # # open the file using with # with open("example.json") as jf: jfinp = jf.read() # now print out the contents directly print('Here is the JSON in the file:') print(jfinp) # wait for the user to indicate you can go on print("---------------------------") x = input("Press return to continue") # now save it as a dictionary print('Now we decode it;', end=" ") jfdict = json.loads(jfinp) print('its type is', type(jfdict)) print(jfdict) # wait for the user to indicate you can go on print("---------------------------") x = input("Press return to continue") # now save it as a string print('Now we dump it;', end=" ") jfdump = json.dumps(jfdict) print('its type is', type(jfdump)) print(jfdump) # wait for the user to indicate you can go on print("---------------------------") x = input("Press return to continue") # let's see what's there -- access elements # this *depends* on the file being example.json print('Key is glossary') print(jfdict["glossary"]) print('Key is glossary:title') print(jfdict["glossary"]["title"]) # wait for the user to indicate you can go on print("---------------------------") x = input("Press return to continue") # prettyprint it with an indentation of 4 spaces for each level # separate the keys from the values by ": " and the (key, value) # pairs with "," print('Now we prettyprint it') print(json.dumps(jfdict, indent=4, separators=(",", ": "))) # wait for the user to indicate you can go on print("---------------------------") x = input("Press return to continue") # as before, but separate the keys from the values by " -- " print('Now we prettyprint it another way') print(json.dumps(jfdict, indent=4, separators=(",", " -- ")))