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

如何将JSON作为Python函数入参并解决TypeError报错

解决JSON入参传递与解析的 TypeError 问题

原问题代码与报错

自定义函数 leerJSON

def leerJSON(carrito):
    data = json.loads(carrito)
    
    lista_nombres_y_usuarios = []
    for i in range(1):
        #data = json.loads(data1)
        user = data[i]
        nombre = user['name'] 
        username = user['username']
        email = user['email']
        lista_nombres_y_usuarios.append([nombre, username])

    return(nombre, username, email, array)

调用脚本

carrito = '''{
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
}'''
carritojson= json.dumps(carrito, indent = 4) # Conversión a json
[name, username, email, array] = leerJSON(carritojson)
print(name)
print(username)
print(email)
print(array)

报错信息

Traceback (most recent call last):
  File "/home/idein/Escritorio/Factura/prueba.py", line 12, in <module>
    [name, username, email, array] = leerJSON(carritojson)
  File "/home/idein/Escritorio/Factura/funcionLecturaJSON.py", line 36, in leerJSON
    nombre = user['name'] 
TypeError: string indices must be integers

错误原因分析

  1. JSON转换逻辑错误:carrito本身就是JSON格式的字符串,不需要用json.dumps()再次转换。json.dumps()的作用是把Python对象转成JSON字符串,这里把原JSON字符串转成了字符串的JSON编码,导致函数内json.loads(carrito)解析后得到的是原字符串,而非预期的字典。此时data[i]取的是字符串的单个字符,自然无法用['name']这种键索引,触发类型错误。
  2. 函数内部逻辑错误:
    • 解析后的data是单个用户的字典,不是列表,没必要用for i in range(1)循环遍历。
    • 返回值里的array未定义,实际应该返回之前定义的lista_nombres_y_usuarios。

修正后的代码

修正后的 leerJSON 函数

import json

def leerJSON(carrito):
    # 解析JSON字符串为Python字典
    data = json.loads(carrito)
    
    lista_nombres_y_usuarios = []
    # 直接从字典中提取字段,无需循环
    nombre = data['name'] 
    username = data['username']
    email = data['email']
    lista_nombres_y_usuarios.append([nombre, username])

    # 返回正确的变量,替换未定义的array
    return nombre, username, email, lista_nombres_y_usuarios

修正后的调用脚本

import json

carrito = '''{
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org"
}'''
# 直接传入原JSON字符串,无需额外转换
name, username, email, user_list = leerJSON(carrito)
print(name)
print(username)
print(email)
print(user_list)

关键修正点说明

  • 去掉调用脚本中多余的json.dumps(),直接将原始JSON字符串传入函数。
  • 函数内去掉无意义的for循环,直接从解析后的字典中提取字段。
  • 修正返回值中的未定义变量array,改为实际的列表lista_nombres_y_usuarios。
  • 注意原JSON字符串末尾的逗号("website": "hildegard.org",),虽然部分解析器能兼容,但建议去掉以符合标准JSON格式。

内容的提问来源于stack exchange,提问作者DAVID

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 23:36:20