我有一个来自Google电子表格的JSON文件(用于读取电子表格)。
我正在尝试将JSON作为字符串复制到脚本中。
这就是我的方法:
from oauth2client.service_account import ServiceAccountCredentials
import gspread
json_string ='''
{
"type": "service_account",
"project_id": "ID",
"private_key_id": "KEYID",
"private_key": "-----BEGIN PRIVATE KEY-----
......KEY HERE......
-----END PRIVATE KEY-----
",
"client_email": "EMAIL",
"client_id": "ID",
"auth_uri": "URI",
"token_uri": "URI",
"auth_provider_x509_cert_url": "URL",
"client_x509_cert_url": "CLINET"
}
'''
info = json.loads(json_string.replace("'",'"').replace('\r\n', '\\r\\n'), strict=False)
client = gspread.authorize(credentials)
sheet = client.open("Responses").sheet1
...
ERROR OUTPUT -
private_key_pkcs8_pem = json_data['_private_key_pkcs8_pem']
KeyError: '_private_key_pkcs8_pem'
关于如何正确将字符串作为JSON凭证读取的任何建议?
答案 0 :(得分:0)
只是一个想法,不确定是否正确回答了以下问题:您不能在JSON中使用经典的换行符。可能是您的私钥(或您未包含在代码中的其他属性)例如)包含换行符,因此JSON字符串无效。
另请参阅this Stackoverflow post,以获取有关如何在JSON文档中使用换行符的更多信息。
答案 1 :(得分:0)
您需要使用ServiceAccountCredentials.from_json_keyfile_dict
而不是ServiceAccountCredentials.from_json
。
答案 2 :(得分:0)
这对我有用,从字符串初始化凭据,因为我们使用远程 python 客户端并且上传凭据文件并不容易。
SCOPES = ('https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/cloud-platform')
json_data = """{
"type": "service_account",
"project_id": "xxxxxxxx",
"private_key_id": "xxxxxxxxxx",
"private_key": "-----BEGIN PRIVATE KEY-----xxxxxxxx",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robotxxxxxxxx.iam.gserviceaccount.com"
}"""
json_key = js.loads(json_data,strict=False)
credentials = service_account.Credentials.from_service_account_info(json_key,scopes=SCOPES)
my_client_py = pg.authorize(custom_credentials=credentials)