Skip to main content
 首页 » 编程设计

Python,jsonpath : How do I parse with jsonpath correctly

2025年01月19日9jirigala

我有一个实现问题...

#!/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”...在此 url 中。它被传递给一个名为“Price”的类,该类创建传递给包含上述代码的类的变量。

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

这是我要定位的 json...试图获取 rate_float 键:

{ 
  "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 
  } 
} 

当我运行该程序时,它会向我发送整个 json 文件的输出,而不是我尝试通过 jsonpath 使用“bpi.USD.rate_float”定位的特定 key 我正在使用 jsonpath_rw。

如何使用 jsonpath 有效地定位 rate_float 键?

请您参考如下方法:

问题是您可能认为 results 包含来自 Python dict 的纯字符串值。

这实际上不是 jsonpath_rw 返回的内容。如果您查看 https://github.com/kennknowles/python-jsonpath-rw 中的示例你会看到它做的,例如

[match.value for match in jsonpath_expr.find({'foo': [{'baz': 1}, {'baz': 2}]})] 

正如它进一步提到的那样:

The result of JsonPath.find provide detailed context and path data so it is easy to traverse to parent objects, print full paths to pieces of data, and generate automatic ids.

find 实际上返回带有上下文信息的对象列表。如果您想要的只是字符串值,并且您只希望为 JSONPath 表达式获得一个返回值,那么您需要执行如下操作:

results = parse_jsonpath(self.json_key).find(json_dict) 
print(results[0].value)