使用 Python 从 JSON API 中提取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21670239/
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-18 23:22:38  来源:igfitidea点击:

Extract data from JSON API using Python

pythonjsonapiopenurl

提问by Python2014

I go through this part:

我经历了这部分:

How do I extract the data from that URL? I only want to print out the "networkdiff": 58954.60268219.

如何从该 URL 中提取数据?我只想打印出"networkdiff": 58954.60268219.

from urllib import urlopen

url = urlopen('http://21.luckyminers.com/index.php?page=api&action=getpoolstatus&api_key=8dba7050f9fea1e6a554bbcf4c3de5096795b253b45525c53562b72938771c41').read()

print url

This is what the API display as a result from print url command:

这是 API 显示的打印 url 命令的结果:

{
    "getpoolstatus": {
        "version": "1.0.0",
        "runtime": 16.618967056274,
        "data": {
            "pool_name": "21 Coin Pool @ Luckyminers.com",
            "hashrate": 485426748,
            "efficiency": 98.1,
            "workers": 14,
            "currentnetworkblock": 12025,
            "nextnetworkblock": 12026,
            "lastblock": 12023,
            "networkdiff": 58954.60268219,
            "esttime": 521.61956775542,
            "estshares": 241478052.58625,
            "timesincelast": 427,
            "nethashrate": 485426748
        }
    }
}

回答by Sar009

convert the response to json and then read it

将响应转换为 json 然后读取它

from urllib import urlopen
import simplejson as json

url = urlopen('http://21.luckyminers.com/index.php?page=api&action=getpoolstatus&api_key=8dba7050f9fea1e6a554bbcf4c3de5096795b253b45525c53562b72938771c41').read()
url = json.loads(url)

print url.get('getpoolstatus').get('data').get('networkdiff')

回答by scorpiodawg

You can use the jsonmodule to parse out a Python dictionary and get right to the value like so:

您可以使用该json模块来解析 Python 字典并正确获取值,如下所示:

import json
result = json.loads(url)  # result is now a dict
print '"networkdiff":', result['getpoolstatus']['data']['networkdiff']

To do this multiple times (to answer your question in the comments section):

要多次执行此操作(在评论部分回答您的问题):

import json
import urllib

urls = {'joe': 'url1', 'Hyman': 'url2', 'jane': 'url3'}
for who in urls.keys():
    url = urllib.urlopen(urls[who])
    result = json.loads(url)  # result is now a dict
    print 'For %s: "networkdiff":' % who, result['getpoolstatus']['data']['networkdiff']