使用请求将Python转换为CURL-将输出保存到文件

y1aodyip  于 2022-11-13  发布在  Python
关注(0)|答案(3)|浏览(174)

我想把这个BASH代码转换成python脚本:

curl -XN -u user:Pass -X GET -H "Content-Type: application/json" https://jira.company.com/rest/api/2/search?jql=project='"Technology"+AND+summary~"Remove%20User*"+AND+issuetype="Task"+AND+status!="DONE"' | python -m json.tool > /var/lib/rundeck/1.json

到目前为止我有这个

headers = {
    'Content-Type': 'application/json',
}

params = (
    ('jql', 'project="Technology" AND summary~"Remove User*" AND issuetype="Task" AND status!="DONE"'),
)

response = requests.get('https://jira.company.com/rest/api/2/search', headers=headers, params=params, auth=('user', 'Pass'))

print response

作为响应,我得到<Response [200]>
如何将此命令的输出打印到JSON文件(如在bash脚本中)?
使用以下代码获取JSON文件,但不是JSON结构(作为纯文本):

with open('/var/lib/rundeck/1.json', 'w') as outfile:
    outfile.write(response.content)

使用此转换器:
https://curl.trillworks.com/

z5btuh9x

z5btuh9x1#

您可以尝试以下操作

from json_tricks.np import dump

with open('response.json','w') as responseFile:
        dump({'Data': response },responseFile)
zlwx9yxi

zlwx9yxi2#

这很简单:

response.raise_for_status() # throw on failure
with open('/var/lib/rundeck/1.json', 'w') as outfile:
    outfile.write(str(response.json()))
m3eecexj

m3eecexj3#

在Python 2中

import requests
import json

url = '<URL>'
payload = open("data.json")
headers = {'content-type': 'application/json'}
response = requests.post(url, data=payload, headers=headers)

with open("output.json", "w") as outfile:
     json.dump(response.json(), outfile)

相关问题