在Python中解析Json并寻找值

2024-10-03 11:18:53 发布

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

我尝试使用Python和Json库解析以下Json

{"attributes":{"173":{"id":"173","code":"Size","label":"Size","options":[{"id":"352","label":"Footwear-41","products":["78834"]},{"id":"355","label":"Footwear-42","products":["78835"]},{"id":"357","label":"Footwear-42.5","products":["78836"]},{"id":"358","label":"Footwear-43","products":["78837"]},{"id":"361","label":"Footwear-44","products":["78838"]},{"id":"363","label":"Footwear-44.5","products":["78839"]},{"id":"364","label":"Footwear-45","products":["78840"]},{"id":"367","label":"Footwear-46","products":["78841"]}],"position":"0"}},"template":"<%- data.price %>\u00a0 \u20ac","currencyFormat":"%s\u00a0 \u20ac","optionPrices":{"78834":{"oldPrice":{"amount":189.9},"basePrice":{"amount":159.57983093277},"finalPrice":{"amount":189.9},"tierPrices":[]},"78835":{"oldPrice":{"amount":189.9},"basePrice":{"amount":159.57983093277},"finalPrice":{"amount":189.9},"tierPrices":[]},"78836":{"oldPrice":{"amount":189.9},"basePrice":{"amount":159.57983093277},"finalPrice":{"amount":189.9},"tierPrices":[]},"78837":{"oldPrice":{"amount":189.9},"basePrice":{"amount":159.57983093277},"finalPrice":{"amount":189.9},"tierPrices":[]},"78838":{"oldPrice":{"amount":189.9},"basePrice":{"amount":159.57983093277},"finalPrice":{"amount":189.9},"tierPrices":[]},"78839":{"oldPrice":{"amount":189.9},"basePrice":{"amount":159.57983093277},"finalPrice":{"amount":189.9},"tierPrices":[]},"78840":{"oldPrice":{"amount":189.9},"basePrice":{"amount":159.57983093277},"finalPrice":{"amount":189.9},"tierPrices":[]},"78841":{"oldPrice":{"amount":189.9},"basePrice":{"amount":159.57983093277},"finalPrice":{"amount":189.9},"tierPrices":[]}},"priceFormat":{"pattern":"%s\u00a0 \u20ac","precision":2,"requiredPrecision":2,"decimalSymbol":",","groupSymbol":".","groupLength":3,"integerRequired":1},"prices":{"oldPrice":{"amount":189.9},"basePrice":{"amount":159.57983093277},"finalPrice":{"amount":189.9}},"productId":"78842","chooseText":"Choose an Option...","images":[],"index":{"78834":{"173":"352"},"78835":{"173":"355"},"78836":{"173":"357"},"78837":{"173":"358"},"78838":{"173":"361"},"78839":{"173":"363"},"78840":{"173":"364"},"78841":{"173":"367"}},"sku":{"default":"CI6400-100","78834":"CI6400-100-Footwear-41","78835":"CI6400-100-Footwear-42","78836":"CI6400-100-Footwear-42.5","78837":"CI6400-100-Footwear-43","78838":"CI6400-100-Footwear-44","78839":"CI6400-100-Footwear-44.5","78840":"CI6400-100-Footwear-45","78841":"CI6400-100-Footwear-46"},"stock":{"78834":{"is_salable":true,"qty":1},"78835":{"is_salable":true,"qty":2},"78836":{"is_salable":true,"qty":3},"78837":{"is_salable":true,"qty":3},"78838":{"is_salable":true,"qty":3},"78839":{"is_salable":true,"qty":1},"78840":{"is_salable":true,"qty":3},"78841":{"is_salable":true,"qty":1}}}

我想得到特定鞋码的“产品”值,例如,如果我想要42码,请找78835

我尝试了两种方法:

1

tex=THEJSONTEXT
jsn=json.loads(tex)
jsn['attributes']['173'].get("products","")

但这对我没用。 所以我尝试了版本2:

import re
prod=re.findall('"Footwear-42","products":["\d\d\d\d\d"]', tex)

即使这样对我也没用


Tags: idtrueisamountlabelproductsqtyfootwear
2条回答
>>> jsn['attributes']['173'].keys()
dict_keys(['id', 'code', 'label', 'options', 'position'])

正如您所看到的,产品不在那里,这就是代码不起作用的原因。您正确地解析了JSON

稍微格式化一下JSON

{
  "attributes": {
    "173": {
      "id": "173",
      "code": "Size",
      "label": "Size",
      "options": [
        {
          "id": "352",
          "label": "Footwear-41",
          "products": [
            "78834"
          ]
        },
        {
          "id": "355",
          "label": "Footwear-42",
          "products": [
            "78835"
          ]
        },
        {
          "id": "357",
          "label": "Footwear-42.5",
          "products": [
            "78836"
          ]
        },

... much more

深入研究JSON会更容易一些。我看到的唯一与大小相关的属性是各种选项的label键。对吗?如果是这样的话,您就必须对键进行筛选,然后options列表才能执行您想要的操作

所以。。假设选项列表是这样分配的:

options = obj['attributes']['173']['options']

然后,您可以将列表向下筛选到您想要的产品,如下所示:

>>> size = 42
>>> list(filter(lambda x: x['label'][-1 * len(str(size)):] == str(size), options))
[{'id': '355', 'label': 'Footwear-42', 'products': ['78835']}]

那么,lambda x: x['label'][-1 * len(str(size)):]做什么呢?这是一个lambda,它有效地做到了:

size = 42
def filter_product(product_object):
    label = product_object['label']
    product_size = [-1 * len(str(size)):]  # get the last digits of the str that are the size
    if str(size) == product_size:
        return True
    else:
        return False

我根据大小float/int的长度查看标签的最后n位。然后我把它和你想要的尺寸比较一下,如果是一样的,那么这就是你要找的产品

实际上还有一个层次的嵌套。试试下面的

for i in jsn['attributes']['173']["options"]:
    print(i["products"])

而且options是一个列表

相关问题 更多 >