python - 如何在 Smartsheet Python SDK 中使用搜索结果?
问题描述
启动程序后
results = smart.Search.search("2244113312180")
print(results)
获取数据
{"results":
[{"contextData": ["2244113312180"],
"objectId": 778251154810756,
"objectType": "row",
"parentObjectId": 3648397300262788,
"parentObjectName": "Sample Sheet",
"parentObjectType": "sheet",
"text": "2244113312180"},
{"contextData": ["2244113312180"],
"objectId": 7803446734415748,
"objectType": "row",
"parentObjectId": 3648397300262788,
"parentObjectName": "Sample Sheet",
"parentObjectType": "sheet",
"text": "2244113312180"}],
"totalCount": 2}
如何在我的程序中正确使用它们?请提供正确的用法示例。
以及如何找出找到值“2244113312180”的id_column?
new_row = smartsheet.models.Row()
new_row.id = results.objectId
对不起,我没有马上写错误。我无法使用结果中的属性。细绳:
new_row.id = results.objectId
导致错误
AttributeError: 'SearchResult' object has no attribute 'objectId'
感谢您的任何帮助!
PS我找到了怎么做。
results = smart.Search.search("2244113312180")
text = str(results)
json_op = json.loads(text)
for i in json_op["results"]:
new_row = smartsheet.models.Row()
new_row.id = i["objectId"]
我不知道这是否是一个好的解决方案。
解决方案
根据 Smartsheet API 文档中的SearchResultItem 对象定义,搜索结果项永远不会包含有关值所在列的信息。如您发布的 JSON 结果所示,如果在工作表的行中找到指定的值(即,在该行包含的任何单元格中),则相应的搜索结果项将识别工作表 ID ( parentObjectId
) 和行标识 ( objectId
)。
然后,您可以使用这两个值来检索行,如文档的Get Row部分所述:
row = smartsheet_client.Sheets.get_row(
4583173393803140, # sheet_id
2361756178769796 # row_id
)
然后您可以遍历row.cells
数组,检查value
每个单元格的属性以确定它是否与您之前搜索的值匹配。当您找到cell
包含该值的对象时column_id
,该对象的属性cell
将为您提供匹配值所在的列 ID。
更新:
感谢您在原始帖子中澄清信息。我正在更新此答案以提供一个完整的代码示例,该示例实现了我之前描述的方法。希望这有帮助!
此代码示例执行以下操作:
- 在 Smartsheet 中的所有内容(正在使用的 API 令牌的持有者可以访问)中搜索字符串值
- 遍历搜索结果项以处理任何“行”结果(即,字符串出现在工作表单元格内的任何位置)
- 用字符串替换工作表(的单元格)中的任何出现
new value
# set search criteria
query = '2244113312180'
# search everything
search_results = smart.Search.search(query)
# loop through results
# (acting upon only search results that appear within a row of a sheet)
for item in search_results.results:
if item.object_type == 'row':
# get row
row = smart.Sheets.get_row(
item.parent_object_id, # sheet_id
item.object_id # row_id
)
# find the cell that contains the value and update that cell value
for cell in row.cells:
if cell.value == query:
# build new cell value
new_cell = smartsheet.models.Cell()
new_cell.column_id = cell.column_id
new_cell.value = "new value"
new_cell.strict = False
# build the row to update
new_row = smartsheet.models.Row()
new_row.id = item.object_id
new_row.cells.append(new_cell)
# update row
result = smart.Sheets.update_rows(
item.parent_object_id, # sheet_id
[new_row])
推荐阅读
- ruby - Ruby web scraper 与浏览器结果不同
- php - 无法使我的数组排序函数返回正确的总数
- python - 使用凭据列表批量登录和执行任务
- c# - MongoDB .NET:一对多?多对多?
- woocommerce - 为收到的 woocommerce 电子邮件订单添加具有 ACF 值的占位符
- flutter - Flutter - 在 GridView 中禁用滚动,直到孩子填满高度
- android - 使用 firebase 分析,记录和查看个人用户上次登录时间
- r - 将数据拆分为按标签分层的训练和测试
- spring-webflux - 使用 Flux.merge() 的竞争条件
- python - 如何在python中使来自多个页面的抓取数据数组长度相同?