无法在Python中保存JSON文件。

huangapple go评论89阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年1月6日 20:58:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/59612554.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定