使用Python 3加载JSON对象时遇TypeError错误求助
Hey there! Let's break down why you're hitting this error and get it fixed right away.
What's causing the issue?
The json.loads() function is built to turn JSON-formatted strings into Python dictionaries. But in your code, customerData is already a native Python dictionary—not a string. That's exactly why Python throws that TypeError: it's expecting a string/bytes input, but you're passing a dict directly.
How to fix it
There are two common scenarios here, depending on where your data comes from:
Scenario 1: Your data is already a Python dictionary
If you're working with the customerData dict you defined directly, you don't need json.loads() at all. Just use the dictionary as-is:
customerData = { "Joe": {"visits": 1}, "Carol": {"visits": 2}, "Howard": {"visits": 3}, "Carrie": {"visits": 4} } def greetCustomer(customerData): # No json.loads needed—directly interact with the dict for customer_name, customer_info in customerData.items(): print(f"Hi {customer_name}! You've visited {customer_info['visits']} times.") # Call the function with your existing dict greetCustomer(customerData)
Scenario 2: Your data starts as a JSON string
If you're getting your data from a source that gives you a JSON string (like an API response, text file, or user input), then you would use json.loads() to convert it to a dict. Here's an example:
import json # This is a JSON-formatted string (note the triple quotes wrapping it) customerData_str = '''{ "Joe": {"visits": 1}, "Carol": {"visits": 2}, "Howard": {"visits": 3}, "Carrie": {"visits": 4} }''' def greetCustomer(customerData_str): # Convert the JSON string to a Python dict response = json.loads(customerData_str) for customer_name, customer_info in response.items(): print(f"Hi {customer_name}! You've visited {customer_info['visits']} times.") # Call the function with the JSON string greetCustomer(customerData_str)
Bonus: Converting a dict to a JSON string
If you ever need to go the other way (turn a Python dict into a JSON string), use json.dumps() instead:
import json customerData = { "Joe": {"visits": 1}, "Carol": {"visits": 2}, "Howard": {"visits": 3}, "Carrie": {"visits": 4} } json_string = json.dumps(customerData) print(json_string) # Outputs the JSON-formatted string version of your dict
内容的提问来源于stack exchange,提问作者ChrisJ

