JSON to Python (Reading In JSON Files)
- We use Python’s built-in JSON module with JSON files. Import the JSON module using the following import statement:
![](https://lh4.googleusercontent.com/PzXh9nJKluU8izme5Lfh54jpMk3nthY2sNk3pAv7y0tSU-uNnhDszz3vqKM4LTFHCx9q0duSHYOCp7WFvUEOr6C9xlja1xs2ZlmM-9LqFAJ3fgUVYModUGR61gAkYF53xkce8Y35)
- Use one of the two methods from the JSON module to read in JSON data in Python.
The loads method parses a string of JSON code and turns it into a Python dictionary
jsonstring2dict = json.loads(‘jsonstring’)
The load method translates the data in a JSON file into a Python dictionary.
with open(‘jsonfilename.json’, ‘r’) as f:
json2dict = json.load(f)
EXAMPLE 1 (loads Method)
We have a JSON string we are attempting to read in and convert to a Python Dictionary.
![](https://lh6.googleusercontent.com/E6PH5ueXg6EWHj0QYFdab7IQ6AK0C-qDIreD4tPU23JrXAm_rbjniAbNPO3KI59FqzFt3XyckOoTmUySdmddsk0svMr74H83Q1tRbjvijLxse-PE0Gf-bFdNnwVJ0uEoNYFDn2uS)
Output (a Python Dictionary):
![](https://lh4.googleusercontent.com/K326vn2YD-rmgnvi2odio2P-L2o3hKUFuNbejeIpmlKytaBR7SdH6jWg2LCeLe0yakj_bYKJD_xJbT-o49Kv0Iu8TUXtMfQp1bpqfacbAZPoOStL6UiiCcHIhsuBZICkiiKkgzbI)
EXAMPLE 2 (load Method)
Here, we have a JSON file we wish to convert into a Python dictionary.
Download sample.json
![](https://lh6.googleusercontent.com/Jt5UeW6OzRz4YJj-NAC834V9pNed7Zfov9y8-KCcQVB4qG_TxFEppVw5BVZNjyj7XT5PtLj4rvs8BvDYGsfPowRz3TPVTCbcf2GcNR-3yLjtgwDT5npc8LfmAFGehroVwbYR3A29)
There are two steps to read in a JSON file:
- Open the JSON file
- Load the file using the load method
In Python, we can do both of these steps at once like this:
![](https://lh4.googleusercontent.com/_q-hlOtndV6gPBSWLD8hljQPjElTGsg5btIlnmCPP6T4dQbPgADdrdGRJtO3iF0Llst7KmrO3okQMGXQqpmi5ZrAI5kQIi-N9A7qvC_p0XQ3WuoJqFSfJ5zu7SM_zkjn_AmS7sFD)
Output (Python Dictionary):
![](https://lh3.googleusercontent.com/oeIUY5SEdAejo-EKiXUS2Lm-yImecRfFV3K4h3IChxGz9buRfIc4E6bfmavIsJvAtHZiCKyEHzlX6zsUzpo3EGI2n3dyaXBbvWgeuMszu36uBjnIdruyoZILgPrHMfEBm2yfMAIj)