Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
98: Working with JSON Data
I see this all the time when I'm reviewing code from junior devs: someone receives a response from an API or reads a configuration file, and they immediately try to access a key like data["user_id"], only to have the program crash with a TypeError: string indices must be integers. This happens because of a fundamental misunderstanding of what JSON actually is.
JSON is not a Python Dictionary
The biggest misconception is thinking that JSON *is* a dictionary. It isn't. JSON (JavaScript Object Notation) is a string. It is a specific way of formatting text so that different languages—Python, JavaScript, Ruby, Go—can all agree on how to move data around. When you see JSON in a tutorial, it looks exactly like a Python dict, which is why it's so easy to confuse the two.
Take a look at this mistake:
# This is a JSON string, not a dictionary
json_response = '{"name": "Alice", "role": "Engineer"}'
# This will fail!
print(json_response["name"])
# TypeError: string indices must be integers
In the example above, Python sees json_response as just a long piece of text. When you use ["name"], Python thinks you're trying to slice the string using an index, but you provided a string instead of a number. To Python, that's nonsense.
Parsing Strings into Python Objects
To actually use the data, you have to deserialize it. In Python, we use the json module to turn that string into a real Python dictionary. You'll want to use json.loads() (the 's' stands for string).
import json
json_response = '{"name": "Alice", "role": "Engineer"}'
user_data = json.loads(json_response)
# Now it's a dictionary, and this works perfectly
print(user_data["name"]) # Output: Alice
I usually tell my mentees to remember it this way: loads is "load string." Conversely, when you want to turn a Python dictionary back into a JSON string (maybe to send it back to a server), you use json.dumps() ("dump string").
Handling Actual Files on Disk
You won't always be dealing with raw strings. Most of the time, you'll be reading a .json file from your hard drive. While you could read the file as a string and then use loads(), Python gives us a more direct way: json.load() (no 's' at the end).
This function takes a file object directly. It's cleaner and generally more memory-efficient for larger files.
import json
# Assuming we have a file named 'config.json'
with open('config.json', 'r') as f:
config = json.load(f)
print(f"Connecting to {config['host']} on port {config['port']}")
One thing to watch out for: JSON is stricter than Python. For example, JSON requires double quotes " for keys and strings. Single quotes ' will throw a json.decoder.JSONDecodeError. If you're manually creating JSON strings, stick to double quotes or, better yet, create a dictionary and use dumps() to let Python handle the formatting for you.
📋 Practical Task
Inventory Value Calculator from JSON
You have been given a JSON string representing a warehouse inventory. Your task is to parse this string and calculate the total monetary value of all items in the warehouse.
Requirements:
- Start with the following JSON string:
inventory_data = '[{"item": "Laptop", "price": 1200, "quantity": 5}, {"item": "Mouse", "price": 25, "quantity": 50}, {"item": "Monitor", "price": 300, "quantity": 10}]' - Convert this string into a Python list of dictionaries.
- Iterate through the list, multiplying the
priceby thequantityfor each item. - Print the final total value (e.g., "Total Inventory Value: $X").
There are no comments for now.