【问题标题】:How do I write the Smartsheet response to a file?如何将 Smartsheet 响应写入文件?
【发布时间】:2019-05-24 00:02:12
【问题描述】:

我正在尝试编写一些基本代码来检索工作区列表并将响应写入文件。我认为这可以转储到 JSON 文件中?

感谢您的任何帮助/建议。

我已经获取了示例 .py 文件并将其修改为如下所示 -

# Install the smartsheet sdk with the command: pip install smartsheet-python-sdk
import smartsheet
import logging
import os.path
import json

# TODO: Set your API access token here, or leave as None and set as environment variable "SMARTSHEET_ACCESS_TOKEN"
access_token = None

print("Starting ...")

# Initialize client
smart = smartsheet.Smartsheet(access_token)
# Make sure we don't miss any error
smart.errors_as_exceptions(True)

# Log all calls
logging.basicConfig(filename='rwsheet.log', level=logging.INFO)

response = smart.Workspaces.list_workspaces(include_all=True)
workspaces = response.data


with open('data.json', 'w') as outfile:
    json.dump(workspaces, outfile)


print("Done")

【问题讨论】:

  • 您遇到错误了吗?

标签: python smartsheet-api


【解决方案1】:

我不确定您面临什么问题,但我认为您会遇到 json.dump(workspaces, outfile) 行的问题,因为 workspaces 变量的结果是 list 您需要遍历到打通数据。使用该变量只会打印出指针,如下所示: [<smartsheet.models.workspace.Workspace object at 0x10382a4e0>]
要解决此问题,您需要遍历变量的结果并将它们分别打印到文件中。我发现这篇关于将输出打印到文件的帖子here。答案提供了三种方法,我能够让它们中的每一种都使用循环迭代结果。
一个例子:

import smartsheet

smar_client = smartsheet.Smartsheet(<ACCESS_TOKEN>)

response = smar_client.Workspaces.list_workspaces(include_all=True)
workspaces = response.data

with open('workspaces.json', 'w') as f:
  for workspace in workspaces:
    print(workspace, file=f)

运行它给了我一个workspaces.json 文件,该文件位于我运行脚本的同一目录中,其中包含workspace 对象列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多