【问题标题】:Python to CURL using requests-save output to filePython 到 CURL 使用请求保存输出到文件
【发布时间】:2018-04-02 10:40:58
【问题描述】:

我想将此 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/

【问题讨论】:

标签: python json curl pycurl


【解决方案1】:

你可以试试下面的

from json_tricks.np import dump

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

【讨论】:

  • TypeError: class "cookielib.DefaultCookiePolicy" does not have a __new__ method; perhaps it is an old-style class not derived from object; add object` 作为基类对其进行编码` Python 2.7.5
  • 当你print response 时你得到json 响应还是只得到200
  • 只有200 但是当添加额外的代码(发布有问题)然后得到纯文本文件
  • 对不起,我没明白。你怎么能只打印200 并且在输出代码之后打印json信息。 response 变量在打印时应该已经包含 json 信息。当你的意思是纯文本文件时,你的意思是你只看到一个 json 行吗?如果是这样,那不是问题,只是没有美化。
  • 在打印响应中我只得到 200 是的,我只看到一个 JSON 行,但对其进行了测试并可以解析它,所以它可以工作:),谢谢!!
【解决方案2】:

很简单:

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

【讨论】:

  • outfile.write(response.json()) TypeError: expected a character buffer object
  • 这个有效:with open('/var/lib/rundeck/1.json', 'w') as outfile: outfile.write(response.content) 但内容不是 JSON 格式
  • @Milister:我将其更新为使用 str() 将 JSON 转换回字符串。但是当你说“内容不是 JSON 格式”时,你能说出它是什么格式的吗?
  • 文件只包含2-3行而不是百行
【解决方案3】:

在 Python2 中

import requests
import json


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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多