在 Python 中从 curl 读取 JSON 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22366748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:49:04  来源:igfitidea点击:

Reading JSON files from curl in Python

pythonjsoncurl

提问by Malluce

Let's say I have a command in Python that looks like

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

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

What it does right now is GET from the place I curl and store the result in result.json, then I open it to read it. I wonder if there's way I can read it directly without storing to local first?

它现在所做的是从我卷曲的地方 GET 并将结果存储在 result.json 中,然后我打开它来阅读它。我想知道是否有办法直接读取它而无需先存储到本地?

采纳答案by Esparta Palma

You can use the stdlib (json& urllib2) to avoid the use of external commands:

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

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

But I'd recommend to use requeststo simplify your code. Here a sample from the docs:

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

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 Update

Python 3 更新

Please consider that in Python3 urllib2 does not exists anymore, you should use urllibwhich comes in the standard library

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

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

回答by jfs

In general, if you have a command that prints to its stdout then you could get the output without storing it on the disk using subprocess.check_output:

通常,如果您有一个打印到其标准输出的命令,那么您可以使用以下命令获取输出而无需将其存储在磁盘上subprocess.check_output

from subprocess import check_output

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

In your case, you could use urllib2or requestsPython modules instead of curlcommand as shown in @Esparta Palma's answer.

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