OOP - 访问对象数据

OOP - Accessing Object Data

如果这是一个重复或简单的问题,我们深表歉意。

我最近一直在学习 Python(花了很多年编写简单的 MATLAB 脚本)。我已经开始探索面向对象编程和 JSON.

我正在尝试使用 API 从服务器收集数据。当返回对象时,我基本上可以很好地使用语法来访问特定的数据字段。但是,我正在努力解决一个问题。我有一个行对象:

row = {"totalCount": 1, "results": [{"parentObjectId": 887, "contextData": ["Row 1"], "parentObjectType": "sheet", "objectId": 599, "text": "Text", "parentObjectName": "Data", "objectType": "row"}]}

我正在尝试访问单个结果 (result[0]) 的 "objectId" 属性。

我已尝试 rowId = row.results[0].objectId 但收到错误消息“'SearchResultItem' 对象没有属性 'objectId'”。

我也试过 rowId = row.results[0]['objectId'] 但得到错误“'SearchResultItem' 对象没有属性 '__getitem__'”。

--- 编辑:

print(reportingRow.results[0]['objectId'])
Traceback (most recent call last):

  File "<ipython-input-46-14e026c273e3>", line 1, in <module>
   print(reportingRow.results[0]['objectId'])

TypeError: 'SearchResultItem' object has no attribute '__getitem__'

我正在使用一个名为 Smartsheet 的工具。我正在使用 search_sheet 请求。 API 文档 (http://smartsheet-platform.github.io/api-docs/#search-sheet) 说 'SearchResultItem' 是一个包含许多属性的对象。它没有提供更多信息。

可在此处找到 Smartsheet 模型:https://github.com/smartsheet-platform/smartsheet-python-sdk/tree/master/smartsheet/models。我目前正在查看 search_result.py 和 search_result_item.py 以找到 answer/clues.

--- 编辑结束

感谢您的帮助!

请尝试:

rowId = row['results'][0]['objectId']

您的图书馆代码清楚地表明,SearchResultItema property .object_id

print(reportingRow.results[0].object_id)  # this works just fine

你的问题不是dictionary/JSON-related,因为你没有使用字典。您正在使用围绕这些词典的自定义对象。