Scrape json objects that start with [some text]

Viewed 41

I'm using BS4 to scape an eCommerce site and I need to check the stock. Most of the products I can check the stock scraping the product json for:

stock = (jsonData['stocks']['XZ32_'])

because the json object is something like:

"stocks": {
  "XZ32_": 81
}

But sometimes it changes and looks something like this:

"stocks": {
  "XZ32_33935": 81
}

This number changes on every single product.

Question: Is there any way to get the value for a key in the json object that starts with "XZ32_" ?

1 Answers

You can use this example to get value of key that starts with XZ32_:

jsonData = {
    "stocks": {
      "XZ32_33935": 81
    }
}

xz32 = next(jsonData['stocks'][k] for k in jsonData['stocks'] if k.startswith('XZ32_'))
print(xz32)

Prints:

81

More elaborate example (returns default if no key is found):

jsonData = {
    "stocks": {
      "XZ32_33935": 81
    }
}

def get_value(d, key_start, default=None):
    for k in d:
        if k.startswith(key_start):
            return d[k]
    return default

x32 = get_value(jsonData['stocks'], 'XZ32_')
print(x32)
Related