You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python 3加载JSON对象时遇TypeError错误求助

Fixing the TypeError: JSON object must be str, bytes or bytearray, not 'dict'

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:00:06