【问题标题】:getting object has no attribute 'get' or object is not subscriptable when trying to access JSON response converted to DTO尝试访问转换为 DTO 的 JSON 响应时,获取对象没有属性“get”或对象不可下标
【发布时间】:2021-05-06 09:44:31
【问题描述】:

我正在尝试访问 JSON 响应,我正在尝试使用 get() 方法,但我收到“对象没有属性 'get'”错误,当我使用 [] 尝试时,我得到了“对象不可下标”错误。 响应是有效的,因为我在 get 操作之前打印了它,一切看起来都很好。 之前解析响应没有这样的问题。

def get_return_params_and_identifiers(return_params):
    print("******** res start **********")
    print(return_params)
    print("******** res end **********")
    return_parameters = return_params.get('return_parameters')

这是回复的一部分:

******** res start **********
{'levels': None,
 'return_parameters': [{'identifier_name': 'Premium',
                        'level': None,
                        'return_parameter_name_pk': 1258407,
                        'return_parameters_details': [{'base_parameter_name': 'Premium '
                                                                              'Parameter',
                                                       'base_parameter_pk': 1149913,
                                                       'class_value': None,
                                             ....
                                             ....

有没有人遇到过这种情况并知道发生了什么。

编辑:

尝试使用 json.loads() 但响应是 DTO 而不是 JSON,因此出现另一个错误: TypeError: JSON 对象必须是 str、bytes 或 bytearray,而不是 DTO

DTO 类如下:

class ReturnParametersContainerDTO(object):
    """NOTE: This class is auto generated by the swagger code generator program.

    Do not edit the class manually.
    """
    """
    Attributes:
      swagger_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    swagger_types = {
        'return_parameters': 'list[ReturnParameterDTO]',
        'levels': 'LevelsDTO'
    }

    attribute_map = {
        'return_parameters': 'returnParameters',
        'levels': 'levels'
    }

它清楚地表明类中的项目是字典,但不知何故它无法识别它。

【问题讨论】:

  • print(type(return_params)) 的结果是什么?
  • Type: 我已经用这个 DTO 更新了帖子

标签: python json


【解决方案1】:

好的,我解决了这个问题。 这是 OpenApi 生成的 DTO 类的实现中的一些东西,将其显示为字典(在 to_str() 方法中,它调用 to_dict() 并将其打印为字典)但实际上这些只是属性,因此使用了 to_dict 方法() (在 swagger 生成的类中)将其转换为字典。 现在一切正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    • 2018-03-07
    • 2017-11-02
    • 2017-01-18
    • 2017-10-17
    • 2022-07-21
    相关资源
    最近更新 更多