Parsing a JSON file using the json module

The next step is to use json module to read and parse the data in the scf_data.json file. The following instructions describe how to use the json module:

  1. In the process_data.py file, open the json module using an import statement as follows. Not surprisingly, the name used to import the module is json.
a built-in module or an import json

inFile = open("data/input_data.json",'r')
print(inFile.read())
inFile.close()
  1. The load() function of the json module reads and parses the data in a JSON file. Use the json.load() function to load the contents of the file object and assign the result to a variable called scf_data. In the following continuation of , the scf_data variable contains the parsed data from the JSON file. Note that the call to json.load() should be placed between the opening and closing of the input file:
import json

inFile = open("data/input_data.json",'r')
scf_data = json.load(inFile)
print(inFile.read())
inFile.close()
The syntax used to call the load function of the json module ('json.load()') is sometimes a bit confusing for beginners. This syntax has to do with a programming structure called objects. An object is a Python structure consisting of a collection of functions and variables. Objects are both a way of organizing code conceptually and of avoiding conflicts in variable and function names.
In this book, I will not create any objects directly. However, functions and properties of objects will be used frequently, so it is helpful to be familiar with the syntax to use objects.
In this case, load() is a function that belongs to the JSON object, which is created when the json module is imported. As the load() function belongs to the JSON object, the load is called by writing json.load().
  1. Next, instead of printing the raw data, print the scf_data variable containing the parsed JSON data as is done in the following continuation of process_data.py:
import json

inFile = open("data/input_data.json",'r')
scf_data = json.load(inFile)
print(scf_data)
inFile.close()
  1. Go ahead and run the program. You should see the parsed JSON data printed to the output:

In the Terminal output, the appearance of the parsed data may not look that different from that of the raw data. However, the two are quite different. In the raw format, the data is simply represented as a Python string. In the parsed format, however, the data is represented as a collection of nested Python dictionaries and Python lists. This means that it is possible to manipulate the data programmatically.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset