Python,jsonpath:如何正确解析jsonpath? [英] Python, jsonpath: How do I parse with jsonpath correctly?

查看:130
本文介绍了Python,jsonpath:如何正确解析jsonpath?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实施问题...

I have an implementation question...

#!/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"的值是此URL中的"bpi.USD.rate_float"....它将传递给名为"Price"的类,该类将创建变量,该变量传递给包含以上代码的类.

The value that gets passed for the "json_key" is "bpi.USD.rate_float"... inside this url. It gets passed to a class called "Price", which creates variables that pass to the class that the code above is contained in.

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

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

And here is the json I am targeting... trying to get to the rate_float key:

{
  "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_float"向我发送整个json文件的输出,而不是我尝试通过jsonpath定位的特定键. 我正在使用jsonpath_rw.

When I run the program, it sends me the output of the entire json file, rather than the specific key I am trying to target via jsonpath, using "bpi.USD.rate_float" I'm using jsonpath_rw.

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

How do I target the rate_float key effectively using jsonpath?

推荐答案

问题是您可能认为results包含Python dict中的纯字符串值.

The problem is that you probably think results contains a plain string value from the Python dict.

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

That is not in fact what jsonpath_rw returns. If you look at the examples in https://github.com/kennknowles/python-jsonpath-rw you'll see it do e.g.

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

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

And as it mentions further down:

JsonPath.find的结果提供了详细的上下文和路径数据,因此可以轻松遍历父对象,打印数据的完整路径并生成自动ID.

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表达式获取一个返回值,则需要执行以下操作:

find actually returns a list of objects with contextual information. If all you want is the string value, and you only ever expect to get one return value for your JSONPath expression, you'll need to do something like:

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

这篇关于Python,jsonpath:如何正确解析jsonpath?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆