Python,jsonpath:如何使用jsonpath正确解析?

2024-04-27 00:36:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个实施问题。。。

#!/usr/bin/python

#This is the API for BTC price request. 
# Average all the amounts, and push that to the program

import json
import urllib.request
from jsonpath_rw import parse as parse_jsonpath

class BtcAPI:

    def __init__(self, url, api_id, json_key):
        self.url = url
        self.api_id = api_id
        self.json_key = json_key

    def btc_api_call(self):

        hdr = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' }
        req = urllib.request.Request(self.url, headers=hdr)
        readdata = urllib.request.urlopen(req)
        json_data = readdata.read()

        json_dict = json.loads(json_data)
        results = parse_jsonpath(self.json_key).find(json_dict)
        print(results)


class Price:


    def __init__(self, api_id, url, json_key):

        self.api_id = api_id
        self.url = url
        self.json_key = json_key

    def pass_for_request(self):

        get_price = BtcAPI(self.url, self.api_id, self.json_key)
        get_price.btc_api_call()


def Coindesk():
    coindesk = Price("coindesk","https://api.coindesk.com/v1/bpi/currentprice.json","time.updated")
coindesk.pass_for_request()

为“json_key”传递的值是“bpi.USD.rate_float”。。。在这个网址里面。它被传递给一个名为“Price”的类,该类创建传递给上述代码所包含的类的变量。

coindesk = Price("coindesk","api.coindesk.com/v1/bpi/currentprice.json", "bpi.USD.rate_float")

这是我的目标json。。。正在尝试获取速率浮动键:

{
  "time": {
    "updated": "Feb 5, 2018 18:34:00 UTC",
    "updatedISO": "2018-02-05T18:34:00+00:00",
    "updateduk": "Feb 5, 2018 at 18:34 GMT"
  },
  "disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
  "chartName": "Bitcoin",
  "bpi": {
    "USD": {
      "code": "USD",
      "symbol": "$",
      "rate": "7,004.9588",
      "description": "United States Dollar",
      "rate_float": 7004.9588
  }
}

当我运行这个程序时,它会使用“bpi.USD.rate戥u float”通过jsonpath向我发送整个json文件的输出,而不是我试图通过jsonpath指向的特定键 我在用jsonpath。

如何使用jsonpath有效地将速率浮动键作为目标?


Tags: thekeyselfapiidjsonurlrate