繁体   English   中英

从json响应python中提取值?

[英]Extract value from json response python?

我正在向端点发出请求并获得以下格式的 json 响应。

r = requests.get(url)
print(r.json())

{"context":"product=fhvh, price=25,product=vfjvnf,price=37,product=fvfv,price=3.....}

我想遍历它们并计算价格点超过 22 的产品的数量。

我怎么能得到那个? 我最初尝试循环遍历 json 响应,但由于输出的格式,我不相信这会起作用。 有更好的解决方案吗? 我如何首先将响应转换为字典或元组? 有人能帮我吗。 谢谢你。

这是最糟糕的解决方案,它依赖于响应总是有productprice ,并且可能非常不可靠。

r = requests.get(url)
data = r.json()

context=data.get('context')
elements = context.split(',')
chunks=[elements[i:i + 2] for i in range(0, len(elements), 2)]
print(chunks)
[['product=fhvh', ' price=25'], ['product=vfjvnf', 'price=37'], ['product=fvfv', 'price=3']]

我会研究像 Pandas 这样的大数据使用的数据处理库,它们可能有更可靠的方法来做这件事。

更新

r = requests.get(url)
data = r.json()

context=data.get('context')
elements = context.split(',')
chunks=[elements[i:i + 2] for i in range(0, len(elements), 2)]
print(chunks)

product_list = []
for item in chunks:
     obj1=item[0].split('=')
     obj2=item[1].split('=')
     product = { obj1[0].strip(): obj1[1].strip(), obj2[0].strip(): float(obj2[1].strip())}
     product_list.append(product)

print(product_list)

for product in product_list:
     if product.get('price') > 22.0:
             print(product)

您的问题是您拥有的有效负载不是 JSON,而是某种替代格式。 我的建议是将context的每个条目转换为一个对象:

class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = float(price)

def parse_data(resp):

    # First, read in the JSON
    raw_data = r.json()
 
    # Next, split the context field in the JSON into a list-of-tuples
    # where each item represents a key and value.
    parsed_data = [tuple(item.strip().split('=')) for item in raw_data["context"].split(',')]
   
    # Finally, convert each product to our type and return the list of them
    # This assumes that the payload contains a product followed by a price
    return [Product([i][1], y[i + 1][1]) for i in range(0, len(y), 2)]

r = requests.get(url)
filtered = [product for product in parse_data(r) if product.price > 22]

此代码遵循关注点分离并产生您想要的输出(所有价格大于 22 的产品)。 话虽如此,这在很大程度上依赖于对从您请求的 API 返回的内容的假设。 您需要添加数据检查以确保您没有收到错误数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM