Python Tutorial: Working with JSON Data using the json Module
Introduction to JSON in Python
Understanding JSON
- JSON (JavaScript Object Notation) is a widely used data format for storing information, commonly encountered when fetching data from online APIs or configuration files.
- Despite its name, JSON is independent of JavaScript and has libraries available in most programming languages for parsing and generating JSON data.
Loading JSON Data into Python
- A valid JSON string can resemble a Python dictionary; it consists of key-value pairs where values can be arrays or objects.
- To load a JSON string into a Python object, the
json.loads()method is utilized, converting the string into a dictionary that can be easily manipulated.
Conversion Table from JSON to Python
- The conversion process includes:
- JSON objects → Python dictionaries
- JSON arrays → Python lists
- Strings remain strings, integers stay integers, booleans convert to capitalized True/False, and null becomes None.
Accessing Data in Loaded Objects
- After loading the data as a dictionary, accessing specific keys allows for easy manipulation; for example, accessing an array of people stored under the "people" key converts it into a list.
- Iterating through this list enables access to individual objects (dictionaries), allowing extraction of specific attributes like names.
Dumping Python Objects Back to JSON
Modifying and Dumping Data
- To convert modified Python objects back into a JSON string, use
json.dumps(), which allows for customization such as removing certain keys before dumping.
- Adding an
indentargument during dumping enhances readability by formatting the output with specified indentation levels.
Sorting Keys in Output
- The
sort_keysargument can be included when dumping to sort keys alphabetically in the resulting JSON string.
Working with Local JSON Files
Loading from Files
- To load data from local files, use
json.load()after opening the file with a context manager (with open(...)) which ensures proper handling of file resources.
Looping Through Loaded Data
- Once loaded, similar looping techniques apply as with strings; you can access nested structures like states within the loaded data easily.
Writing Modified Data Back to Files
Saving Changes to New Files
- After modifying data (e.g., removing certain fields), write back using
json.dump(), ensuring you open the target file in write mode ('w').
Formatting Output on Write
- Just like when dumping strings, adding an indent parameter while writing improves readability of saved files.
Real-world Application: Fetching API Data
Using Public APIs
- Demonstrates how websites return data in JSON format via APIs; an example involves fetching currency conversion rates using Yahoo Finance's API.
Parsing API Responses
- Utilize built-in modules like
urllibor third-party libraries for making requests. The response needs parsing into usable formats via methods likejson.loads().
Utilizing Conversion Rates
Creating Usable Dictionaries
- Construct dictionaries mapping currency names to their respective conversion rates for quick access during calculations.
Performing Currency Conversions
- Example calculations demonstrate converting USD amounts into other currencies using fetched rates. This showcases practical applications of working with real-time financial data.
Conclusion and Further Learning Opportunities
Encouragement for Engagement
- Viewers are encouraged to ask questions about content covered and share videos if they find them useful. Support options include liking videos or contributing through platforms like Patreon.
Turn any video into a summary like this
YouTube links, meetings, lectures — with transcripts, search, and chat.