简体   繁体   English

在Python中解析Json并找到一个值

[英]Parsing Json in Python and find a value

I am trying to parse following Json using Python and the json library 我正在尝试使用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}}}

I want to get the 'products' value for a specific footwear size, ex. 我想获得特定鞋类尺寸的“产品”价值,例如。 if I want it for 42, find 78835. 如果我要42,请找到78835。

I tried to do it in two ways: 我试图通过两种方式做到这一点:

1. 1。

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

But this doesn't work for me. 但这对我不起作用。 So I tried version 2: 所以我尝试了版本2:

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

And even this didnt work for me.... 甚至这对我也不起作用。

Actually there is one more level of nesting. 实际上,还有一层嵌套。 Try the below. 请尝试以下。

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

Also the options is a list. 这些options也是一个列表。

>>> jsn['attributes']['173'].keys()
dict_keys(['id', 'code', 'label', 'options', 'position'])

As you can see product isn't there, which is why the code isn't working. 如您所见,产品不存在,这就是代码无法正常工作的原因。 You're correctly parsing the JSON. 您正在正确解析JSON。

Formatting the JSON just a bit 稍微格式化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

And it gets a little easier to drill down into the JSON. 向下钻取JSON变得容易一些。 The only attribute I see relating to size is in the label key for the various options. 我看到的与尺寸有关的唯一属性是各种选项的label键。 Is that correct? 那是对的吗? If so, you'll have to filter on the keys then for the options list to do what you want. 如果是这样,则必须筛选键,然后options列表才能执行您想要的操作。

so.. imagine the options list is assigned like this: 所以..想象选项列表是这样分配的:

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

Then you can filter the list down to the products you want like this: 然后,您可以像这样过滤列表到所需的产品:

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

so, what does lambda x: x['label'][-1 * len(str(size)):] do? 那么, lambda x: x['label'][-1 * len(str(size)):]什么作用? It's a lambda which effectively does this: 这是一个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

I look at the last n digits of the label based on how long the size float/int is. 我根据float / int的大小看标签的最后n位数字。 And then I compare that to the size you want, and if it is the same, then this is the product you're looking for. 然后将其与您想要的尺寸进行比较,如果相同,则这是您要寻找的产品。

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

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