Skip to Content
Course content

98: Working with JSON Data

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 price by the quantity for each item.
  • Print the final total value (e.g., "Total Inventory Value: $X").
Rating
0 0

There are no comments for now.

to be the first to leave a comment.