【问题标题】:Reading JSON files from curl in Python在 Python 中从 curl 读取 JSON 文件
【发布时间】:2014-03-13 00:28:22
【问题描述】:

假设我有一个 Python 中的命令,看起来像

command = 'curl ...etc" > result.json'
subprocess.call(command, shell = True)
file = open("result.json").read()

它现在所做的是从我 curl 的地方获取 GET 并将结果存储在 result.json 中,然后我打开它来阅读它。不知道有没有什么方法可以直接读取而不需要先存储到本地?

【问题讨论】:

    标签: python json curl


    【解决方案1】:

    您可以使用标准库(json & urllib2)来避免使用外部命令:

    import json
    import urllib2
    url = "http://httpbin.org/get"
    response = urllib2.urlopen(url)
    data = response.read()
    values = json.loads(data)
    

    但我建议使用requests 来简化您的代码。这是来自文档的示例:

    import requests
    r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
    r.status_code
    200
    r.headers['content-type']
    'application/json; charset=utf8'
    r.encoding
    'utf-8'
    r.text
    u'{"type":"User"...'
    r.json()
    {u'private_gists': 419, u'total_private_repos': 77, ...}
    

    Python 3 更新

    请考虑在 Python3 中 urllib2 不再存在,您应该使用标准库中的urllib

    req = urllib.request.Request(url)
    response = urllib.request.urlopen(req)
    data = response.read()
    values = json.loads(data)    
    

    【讨论】:

    • 你可以跳过明确的.read(): values = json.load(urlopen(url))
    【解决方案2】:

    一般来说,如果您有一个打印到其标准输出的命令,那么您可以使用subprocess.check_output 获得输出而不将其存储在磁盘上:

    from subprocess import check_output
    
    output = check_output(['source', 'arg1', 'arg2'])
    

    在您的情况下,您可以使用urllib2requests Python 模块而不是curl 命令,如@Esparta Palma's answer 所示。

    【讨论】:

      【解决方案3】:

      python3使用curl请求数据
      比如下面把 curl 改成 python。

      $ curl -XPOST http://httpbin.org/post -H "Content-Type:application/json" -d '{"attribute":"value"}'
      

      使用$ python -m pip install urllib3安装urllib3


      import urllib3
      import json
      data = {'attribute': 'value'}
      encoded_data = json.dumps(data).encode('utf-8')
      r = http.request(
          'POST',
          'http://httpbin.org/post',
          body=encoded_data,
          headers={'Content-Type': 'application/json'}
      )
      json.loads(r.data.decode('utf-8'))['json']
      

      打印结果

      {'attribute': 'value'}
      

      参考:https://urllib3.readthedocs.io/en/latest/user-guide.html

      【讨论】:

        猜你喜欢
        • 2014-11-28
        • 2021-10-21
        • 1970-01-01
        • 2017-12-24
        • 1970-01-01
        • 1970-01-01
        • 2020-02-12
        • 2013-12-10
        相关资源
        最近更新 更多