英文:
Not able to save JSON file in Python
问题
以下是翻译好的内容:
可以有人帮我指出下面的函数有什么问题吗?
def RetrieveQuotes(token, appid):
quoteRequestMsg = json.load(open('GetEventHeadlines_Request_1.json'))
quoteURL = 'http://api.trkd.thomsonreuters.com/api/StreetEvents/StreetEvents.svc/REST/StreetEvents_2/GetEventHeadlines_1'
headers = {'content-type': 'application/json;charset=utf-8',
'X-Trkd-Auth-ApplicationID': appid, 'X-Trkd-Auth-Token': token}
print('############### 发送报价请求消息到TRKD ###############')
quoteResult = doSendRequest(quoteURL, quoteRequestMsg, headers)
if quoteResult and quoteResult.status_code == 200:
print('报价响应消息:')
#print(quoteResult.json())
#print(json.dumps(quoteResult.json(), sort_keys=True,indent=2, separators=(',', ':')))
with open('quoteResult.json', 'w') as f:
json.dump(quoteResult, f)
当我打印JSON文件时,一切正常,但我无法将JSON内容保存到本地。
我得到以下错误消息。
类型为'Response'的对象不可JSON序列化
有人能帮我解决这个问题吗?
英文:
Can someone help me in pointing out whats wrong with the below function?
def RetrieveQuotes(token, appid):
quoteRequestMsg = json.load(open('GetEventHeadlines_Request_1.json'))
quoteURL = 'http://api.trkd.thomsonreuters.com/api/StreetEvents/StreetEvents.svc/REST/StreetEvents_2/GetEventHeadlines_1'
headers = {'content-type': 'application/json;charset=utf-8',
'X-Trkd-Auth-ApplicationID': appid, 'X-Trkd-Auth-Token': token}
print('############### Sending Quote request message to TRKD ###############')
quoteResult = doSendRequest(quoteURL, quoteRequestMsg, headers)
if quoteResult and quoteResult.status_code == 200:
print('Quote response message: ')
#print(quoteResult.json())
#print(json.dumps(quoteResult.json(), sort_keys=True,indent=2, separators=(',', ':')))
with open('quoteResult.json', 'w') as f:
json.dump(quoteResult, f)
When i am printing the JSON file its working fine but i am not able to save the contents of the JSON to my local.
I am getting the below error.
Object of type 'Response' is not JSON serializable
Can someone help me on this?
答案1
得分: 1
你需要使用quoteResult.text来获取响应中的原始文本,然后可以将其传递给json.dump()。
英文:
You'll have to use quoteResult.text to get the raw text from the response that you can pass to json.dump()
答案2
得分: 0
quoteResult是响应代码,使用quoteResult.content保存。
英文:
quoteResult is response code use quoteResult.content to save
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论