Python JSON查找特定数据

2024-05-15 17:41:05 发布

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

我有这个JSON文件结构(从网站解析出售的产品)。JSON的一部分:

{
 "shopName": "Shop",
 "promotions": [
  {
   "productName": "Cookies",
   "oldPrice": 11.99,
   "newPrice": 7.99,
   "discount": 33
  },
  {
   "productName": "Butter",
   "oldPrice": 27.15,
   "newPrice": 21.99,
   "discount": 19
  },
  {
   "productName": "Milk",
   "oldPrice": 30.45,
   "newPrice": 21.99,
   "discount": 27
  }
 ]
}

问题是如何仅显示折扣大于给定数字的产品(具有所有功能:名称、旧价格、新价格、折扣)


Tags: 文件json产品网站价格discountshop结构
3条回答

这应该起作用:

data = {
 "shopName": "Shop",
 "promotions": [
  {
   "productName": "Cookies",
   "oldPrice": 11.99,
   "newPrice": 7.99,
   "discount": 33
  },
  {
   "productName": "Butter",
   "oldPrice": 27.15,
   "newPrice": 21.99,
   "discount": 19
  },
  {
   "productName": "Milk",
   "oldPrice": 30.45,
   "newPrice": 21.99,
   "discount": 27
  }
 ]
}

MIN_PRICE = 20

filtered_products = [p for p in data['promotions'] if p['discount'] >= MIN_PRICE]

print(filtered_products)

这张照片是:

[
  {
   "productName": "Cookies",
   "oldPrice": 11.99,
   "newPrice": 7.99,
   "discount": 33
  },
  {
   "productName": "Milk",
   "oldPrice": 30.45,
   "newPrice": 21.99,
   "discount": 27
  }
]

另一种方法是使用filter函数:

filtered_products = list(filter(lambda p: p['discount'] > MIN_PRICE, data['promotions']))

如果您已经解析了JSON,那么可以使用

from typing import Dict, Any

parsed_json = {
"shopName": "Shop",
"promotions": [
    {"productName": "Cookies", "oldPrice": 11.99, "newPrice": 7.99, "discount": 33},
    {"productName": "Butter", "oldPrice": 27.15, "newPrice": 21.99, "discount": 19},
    {"productName": "Milk", "oldPrice": 30.45, "newPrice": 21.99, "discount": 27},
    ],
}


def find_specific_data(num: int, data: Dict[Any, Any]) -> Dict[Any, Any]:
    for value in data["promotions"]:
        if value["discount"] > num:
            print(value)

find_specific_data(26, parsed_json)

In: find_specific_data(26)
Out: {'productName': 'Cookies', 'oldPrice': 11.99, 'newPrice': 7.99, 'discount': 33}
     {'productName': 'Milk', 'oldPrice': 30.45, 'newPrice': 21.99, 'discount': 27}

试试这个

import json, pandas as pd

df=pd.DataFrame(json.loads('{ "shopName": "Shop", "promotions": [  {   "productName": "Cookies",   "oldPrice": 11.99,   "newPrice": 7.99,   "discount": 33  },  {   "productName": "Butter",   "oldPrice": 27.15,   "newPrice": 21.99,   "discount": 19  },  {   "productName": "Milk",   "oldPrice": 30.45,   "newPrice": 21.99,   "discount":27  } ]}')['promotions'])

print(df)

  productName  oldPrice  newPrice  discount
0     Cookies     11.99      7.99        33
1      Butter     27.15     21.99        19
2        Milk     30.45     21.99        27

print(df[df.discount==df.discount.max()])

 productName  oldPrice  newPrice  discount
0     Cookies     11.99      7.99        33

相关问题 更多 >