在Python中从curl读取JSON文件

在Python中从curl读取JSON文件,python,json,curl,Python,Json,Curl,假设我在Python中有一个命令 command = 'curl ...etc" > result.json' subprocess.call(command, shell = True) file = open("result.json").read() 它现在做的是从curl所在的位置获取结果,并将结果存储在result.json中,然后打开它进行读取。我想知道是否有办法不先存储到本地就可以直接读取它?您可以使用stdlib(&)来避免使用外部命令: import json impo

假设我在Python中有一个命令

command = 'curl ...etc" > result.json'
subprocess.call(command, shell = True)
file = open("result.json").read()
它现在做的是从curl所在的位置获取结果,并将结果存储在result.json中,然后打开它进行读取。我想知道是否有办法不先存储到本地就可以直接读取它?

您可以使用stdlib(&)来避免使用外部命令:

import json
import urllib2
url = "http://httpbin.org/get"
response = urllib2.urlopen(url)
data = response.read()
values = json.loads(data)
但我建议使用它来简化代码。以下是文档中的示例:

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, ...}
Python3更新

请考虑在Python 3UrLIb2中不再存在,应该使用标准库

中的哪一个
req = urllib.request.Request(url)
response = urllib.request.urlopen(req)
data = response.read()
values = json.loads(data)    

通常,如果您有一个打印到其标准输出的命令,那么您可以使用
子进程获取输出,而无需将其存储在磁盘上。请检查\u output

from subprocess import check_output

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

在您的情况下,可以使用
urllib2
请求
Python模块,而不是
curl
命令,如所示。

python3使用curl请求数据
例如,在下面的示例中将curl更改为python。

$ curl -XPOST http://httpbin.org/post -H "Content-Type:application/json" -d '{"attribute":"value"}'
使用
$python-m pip安装urlib3


打印结果

{'attribute': 'value'}

ref:

您可以跳过显式的
.read()
values=json.load(urlopen(url))
{'attribute': 'value'}