簡體   English   中英

如何將Smartsheet響應寫入文件?

[英]How do I write the Smartsheet response to a file?

我正在嘗試編寫一些基本代碼來檢索工作區列表並將響應寫入文件。 我以為可以將其轉儲為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")

我不確定您面臨的問題是什么,但我認為您會遇到json.dump(workspaces, outfile)行的問題,因為該workspaces變量的結果是一個list ,您需要對其進行遍歷才能遍歷數據。 使用該變量將只打印出帶有以下內容的指針: [<smartsheet.models.workspace.Workspace object at 0x10382a4e0>]
要解決此問題,您將需要遍歷變量的結果,並將每個結果打印到文件中。 我在這里找到有關將輸出打印到文件的文章。 答案給出了三種方法,我能夠使每種方法與循環遍歷結果的方式一起工作。
一個例子:

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)

運行此命令后,在與workspace對象列表一起運行腳本的同一目錄中,我得到了一個workspaces.json文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM